2

Today when I debug my app into RequestContext putLoginId method, I found the class static ThreadLocal initial failed, the contextData.get() return null, the static contextData only have threadLocalHashCode.

enter image description here

My contextData define in RequestContext class like this:

public class RequestContext { public static final ThreadLocal<Map<String, Object>> contextData = new ThreadLocal<>(); } 

the contextData should be initialed when load the class, so I think it will never be null. But why this happening and what should I do to fix it? Am I missing something?

1
  • 1
    As an aside, storing per-request data such as a login ID in global state (albeit thread-locally, but nonetheless potentially persisted after the request is completed) is not such a good idea. Commented Sep 13, 2021 at 8:43

1 Answer 1

4

the contextData should be initialed when load the class, so I think it will never be null

contextData is initialized when the class is loaded; but you don't actually give it a (per-thread) value, at least in the code shown.


Give your ThreadLocal an initial value with the factory method, for example:

public static final ThreadLocal<Map<String, Object>> contextData = ThreadLocal.withInitial(HashMap::new); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.