I was also confused why I need ThreadLocal when I can just use local variables as they both keep their state inside the thread. But after a lot of searching and experimenting, I see why ThreadLocal is required.
I have found two applications so far -
- Saving specific stream values โโinside the same shared object
- An alternative to passing variables as parameters through N-levels of code
1
If you have two threads running on the same object, and both threads modify this object - then both threads continue to lose their modifications to each other.
In order for this object to have two separate states for each thread, we declare this object or its part ThreadLocal.
Of course, ThreadLocal is only useful because both threads use the same object. If they use different objects, there is no need for ThreadLocal objects.
2
The second advantage of ThreadLocal seems to be a side effect of its implementation.
The ThreadLocal variable can be a .set () stream, and then be .get () anywhere else else..get () will receive the same value that this thread set elsewhere. We will need a globally accessible shell to execute .get () and .set () to actually write the code.
When we do threadLocalVar.set () - it is as if it was placed in some kind of global "map", where this current thread is the key.
As if - someGlobalMap.put (Thread.currentThread (), threadLocalVar);
So, ten layers down when we do threadLocalVar.get () - we get the value that this thread set ten layers up.
threadLocalVar = someGlobalMap.get (Thread.currentThread ());
Thus, a function at the tenth level should not bind this variable as a parameter and can access it with .get (), without worrying about whether it is the right thread.
Finally, since the ThreadLocal variable is a copy for each thread, of course, it does not need synchronization. I misunderstood ThreadLocal earlier as an alternative to synchronization, which is not the case. Itโs just a side effect of this that we donโt need to synchronize the activity of this variable right now.
Hope this helps.