When should one prefer ThreadLocal over synchronization, apart from for the performance improvement? Please explain using a real life example.
When you use ThreadLocal variables these are seen and manipulated by the thread using it ONLY, no other thread can see them. Thread local variables dies when the thread does too. And one should be careful then using ThreadLocal variables when using thread pools.
ThreadLocal variables are put in a special memory space called Thread private stack.
Shared variable are put in the heap memory space where they are shared among all threads and they are either synchronized or not.
So it is more about use case than performance.
One can use ThreadLocal variable to hold a connection to some DB where the connection is associated with the current thread ONLY and no need for other thread to see it and a need to synchronize it. The cache - a shared in memory map or list,for example, however, is shared among all threads in a server application and it must be synchronized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With