ThreadLocal in Java

ThreadLocal is used to create thread-scope variables.

ThreadLocal class is used for creating thread-local variables which can only be read and written by the same thread.

Thus, even if two threads are executing the same code, and the code has a reference to the same ThreadLocal variable, the two threads cannot see each other’s ThreadLocal variables.

Creating a ThreadLocal

private ThreadLocal threadLocal = new ThreadLocal();

You can use Generics like the below:

private ThreadLocal<String> myThreadLocal = new ThreadLocal<String>();

Setting a Value to ThreadLocal

threadLocal.set(“some value”);

Get the ThreadLocal Value

String threadLocalValue = threadLocal.get();

Initializing the ThreadLocal Value

It is possible to set an initial value for a Java ThreadLocal which will get used the first time get() is called – before set() has been called with a new value.

private ThreadLocal<String> threadLocal = new ThreadLocal<String>() {
// Initialize the thread local variable
   @Override protected String initialValue() {
       return “Initial Value”;
Removing the value set in ThreadLocal variable 
We can use the remove method to remove the value set in ThreadLocal variable.
Let’s look into the below code for better understanding.
public class ThreadLocalExample extends Thread{
	public static void main(String[] args) throws InterruptedException {
		Runnable sharedRunnableInstance=new Runnable(){  
			private String str = "";
			private ThreadLocal<String> threadLocal = new ThreadLocal<String>() {
				// Initialize the thread local variable
			    @Override protected String initialValue() {
			        return "Thread Local Variable";
		    public void run() {
				//thread local variable is set
		        //str variable is also set
		        try {
		        	//Goes to sleep for 1000 ms
		        } catch (InterruptedException e) {
                // Reading both the thread local and str variable
		        System.out.println("Thread Local Value:"+threadLocal.get());
		        System.out.println("String value:"+str);
        Thread thread1 = new Thread(sharedRunnableInstance);
        thread1.setName("First Thread");
        Thread thread2 = new Thread(sharedRunnableInstance);
        thread2.setName("Second Thread");
        thread1.join(); //wait for thread 1 to terminate
        thread2.join(); //wait for thread 2 to terminate
Thread Local Value:First Thread
String value:Second Thread
Thread Local Value:Second Thread
String value:Second Thread

In the above code, sharedRunnableInstance instance which is passed to two different threads.

Both threads execute the run() method, and thus sets different values on the ThreadLocal instance variable “threadLocal” and also to the String variable “str”.

However, since it is a ThreadLocal variable, ┬áthe two threads cannot see each other’s values. Thus, they set and get different values.

However, the variable “str” is shared across the threads. For that reason, when the first thread wakes up from sleep, “str” is already updated by second thread.

Leave a Reply

Your email address will not be published. Required fields are marked *