Tuesday, February 5, 2013

ThreadLocal in Java

What is ThreadLocal

ThreadLocal special kind of scope of access. When you put some object or value to this scope on some thread, then this object will be local to that thread. This means that each thread will have it’s own
ThreadLocal variable or reference to some object. One thread can not access/modify other thread’s ThreadLocal variables.

Another important aspect of ThreadLocal is its global access. This means that each method that thread is using can get value/reference from ThreadLocal scope. So, if a thread calls methods from several classes, then all the methods can see the ThreadLocal variable set by other methods.  

Use cases of ThreadLocal

ThreadLocals are usally used in Web Applications, specifically in Servlets. For example you have servlet that is processing some request and you want this request object HttpServletRequest to be accesable in services this servlet is using, but you don't want to send it as parameters in method calls. Because each request is usually processed using separate thread we want to have request object bind
to that thread.
We can do this using Thread Local because ThreadLocal is only valid for the duration of the request.

Another use case for ThreadLocal would be as an alternative to an object or resource pool, when we don't mind creating one object per thread. This should be non-trivial objects that have no requirement to be shared among different threads.

Java provides an ThreadLocal object using which you can set/get thread scoped variables.
You just simply create ThreadLocal object and then use set, remove and get methods.