Java, is it possible to create global variable for thread

In Java 6, is there some sort of thread-bounded context, where I can store and retrieve objects at runtime in the current thread at any code location?

I would need this for debugging purpose. I must assert a certain value in EJB 2.0's EntityContext while ejbStore() is being called is equal with a value further down in the call stack at business logic layer. There is no way to pass the data through interfaces per se specification for debugging purposes. I suspect the cached entity bean contains wrong value in it's context. It is impossible to trace the origin of the value in the current transaction, as WebLogic is in the control of handling the entity beans pooling, caching etc.

Solution would be to put the value in thread-bounded storage at business layer, and retrieve it at the ejbStore() method for comparison. So is this possible? Also, can I be certain WebLogic doesn't spawn new thread for EntityBean callbacks? The former being especially important, as the debugging will be done in production, where the reason for the possible value mismatch must be unambiguous.

Jon Skeet

It sounds like you're looking for ThreadLocal<T>, but I'd generally be careful about using this - it can lead to code where the interaction between two classes is hard to reason about, and it limits how you work with threads later on. (For example, if you decide to parallelize an operation, that could mess everything up.)


See more on this question at Stackoverflow