What's the role of using Map to encapsulate ThreadLocal<Map>?

41 views Asked by At

private ThreadLocal<Map<String,Object>> THREAD_LOCAL=new ThreadLocal()<>

1.To explian the difference encapsulate ThreadLocal by myself and use it's ThreadLocalMap. 2.How to select suitable Data Structures to encapsulate in coding?

1

There are 1 answers

2
Stephen C On

The ThreadLocal.ThreadLocalMap class is an internal class used by the ThreadLocal API to represent the thread locals. It has special properties that make it suitable for that use-case ... and not others.

By contrast

ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal()<>; 

is declaring a thread local that will contain a Map value. THREAD_LOCAL is not the map itself. Rather, it says that any thread have one of those values ... and you access it using the (unhelpfully named) THREAD_LOCAL instance.

In the fullness of time, your thread local's (Map) values will be held in an instance of ThreadLocalMap that is associated with a given Thread. But that is an implementation detail.

1.To explian the difference encapsulate ThreadLocal by myself and use it's ThreadLocalMap.

Basically, these are two different things. The ThreadLocalMap holds all of the thread-local values for a thread. Your Map will be just one of those values.

But you don't need to understand ThreadLocalMap. It is internal. And implementation detail. Not visible to your code. Code to the ThreadLocal API and ignore what happens under the hood. (Or if you are pathologically curious ... download and read the source code for yourself.)

2.How to select suitable Data Structures to encapsulate in coding?

Not sure what you are asking here. But you shouldn't be directly using or depending onThreadLocalMap in your code.