ThreadLocal – an overview


As can be inferred from its name, a ThreadLocal class (javadoc here) provides thread-local variables,  ie variables for which each thread has its own independent copy. ThreadLocals are fairly prevalent in technical frameworks as a means of storing transactions and security contexts on a per-thread/per-request basis:

-> ORM frameworks such as Hibernate and Ibatis use it to bind each thread to a session.

-> A search trough the Koders website for ThreadLocal usages in Java projects returns more than 15000 hits…

Inner workings

Get/Set operations on a ThreadLocal instance respectively read/write to a HashMap of {ThreadLocal instance , Object value} key/value pairs, where the HashMap instance accessed is function of the current thread. Therefore a particular ThreadLocal instance could end up being associated with different object values,  according to which thread is current (and which HashMap is being looked up).

Data structures involved

– Holds a reference to an instance of ThreadLocalMap.

– Defines ThreadLocalMap as a static nested class.
– Declares a custom hashcode, used as a key to locate entries in the ThreadLocalMap

– Maps  ThreadLocals to object values.


Creating a new instance of ThreadLocal:

ThreadLocal threadLocal = new ThreadLocal();

ThreadLocal  object created, and associated with a newly generated ThreadLocal custom hashcode (used to search the ThreadLocalMap in constant time).

Setting a ThreadLocal instance to a specific Object value:

String aString="ThreadLocalTest";

– threadLocal retrieves the ThreadLocalMap referenced from the current thread.
– An entry for the {threadLocal,aString} pair is inserted into the ThreadLocalMap retrieved.

Getting an object from a ThreadLocal instance:

//outputs the value which has previously been set to threadLocal by the current thread...
//assuming we're on the same thread throughout this example, output value will be "ThreadLocalTest"
System.out.println (threadLocal.get());

– threadLocal retrieves the TreadLocalMap referenced from the current Thread.
– The ThreadLocalMap just retrieved returns the entry mapping to threadLocal.
– The Object value (“ThreadLocalTest” String) is extracted from the entry and returned to ThreadLocal.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s