ThreadLocal in Java

The ThreadLocal class in Java is a class that allows us to store and retrieve the values of variables in the same thread. As long as it’s the same thread, you can store a value and retrieve it whenever we want.

You can initialize objects of the ThreadLocal class normally like other classes as follows:

You should clearly specify the data type that the ThreadLocal object will store. In the example above, I declared the data type that the ThreadLocal object will store as String!

Now you can use the set() method of this ThreadLocal object to store the value you want, for example:

To get this value, you can use the get() method as follows:

Results when I run the example:

will be as follows:
If you retrieve the value stored in ThreadLocal in another thread, you will see that the value will be null. Because two different threads will not see the value in each other’s ThreadLocal. For example, if I write more code to read the value of ThreadLocal that I created above:

then when you run it, you will see the following results:

My example has 2 threads: one is the main thread running the application and a new thread that I create. As you can see, the newly created thread does not see the value stored in the main thread’s ThreadLocal.

You can remove the value stored in ThreadLocal using the remove() method:

The result when I run the example will be as follows:

After removing, there are no more values stored in ThreadLocal!

Add Comment