Normally, when an object is shared by multiple threads, depending on the access modifier each thread can access the same field in object and change in that field can be propagated to all other threads.
That’s the default behaviour, but sometimes we want each thread to have its own local copy of the field. In this way, every change to that field will be visible in that thread only.
Java allows us to achieve this behaviour using ThreadLocal variables.
ThreadLocal is a
generic class which can store any kind of object. When object is first get from ThreadLocal variable using Threadlocal.get method, it calls initialValue method if variable is not initialized already.
See MessageQueue class in the example below.
Say, we have a MessageQueue class which contains a ThreadLocal Queue. We want to share an instance of this class with 2 threads, each having its own copy of Queue and inserts 5 items in the Queue.
Without ThreadLocal, each thread will insert data in same Queue.