
ThreadLocal is an object/variable which is specific to each thread. It cannot be shared between multiple objects. Each thread has it’s own Thread Local variable.
The Java ThreadLocal class enables you to create variables that can only be read and written by the same thread
How to create a ThreadLocal Object:
private ThreadLocal tl = new ThreadLocal();
How to set and get the value of the value stored in ThreadLocal Object:
tl.set("James Gosling"); String tlValue = (String) t1.get();
How to remove the value from the ThreadLocal Object:
tl.remove();
We can implement generics as well in the ThreadLocal Object. In the below example, we implement a ThreadLocal Object which can accpet only strings. If it is not string, it will throw a compile time error.
private ThreadLocal<String> stringTL = new ThreadLocal<String>();
Now let’s see an Live example where multiple threads are created and each set their own thread local value.
public class ThreadLocalExmple { public static void main(String[] args) { RunnableTest sharedObject = new RunnableTest(); Thread th1 = new Thread(sharedObject); Thread th2 = new Thread(sharedObject); th1.start(); th2.start(); th1.join(); th2.join(); //th2 waits till th1 completes and then resumes executing. } }
In the above example, 2 threads are created using the same object. Now let’s implement the run method of the RunnbaleTest class.
public class RunnableTest implements Runnable { private ThreadLocal<Integer> tl = new ThreadLocal<Integer>(); @Override public void run() { tl.set( (int) (Math.random() * 1000) ); try { Thread.sleep(500); } catch (InterruptedException e) { } System.out.println(tl.get()); } }
So the above example creates a single Runnable
Test instance which is passed to two threads. Both threads execute the run()
 method, and thus sets different values on the ThreadLocal
 instance. If the access to the set()
 call had been synchronized, and it had not been a ThreadLocal
 object, the second thread would have overridden the value set by the first thread.
However, since it is a ThreadLocal
 object then the two threads cannot see each other’s values. Thus, they set and get different values.