Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should one prefer ThreadLocal over synchronization, apart from for the performance improvement?

When should one prefer ThreadLocal over synchronization, apart from for the performance improvement? Please explain using a real life example.

like image 958
Sriharsha g.r.v Avatar asked Oct 30 '25 18:10

Sriharsha g.r.v


1 Answers

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.

like image 88
Adelin Avatar answered Nov 02 '25 08:11

Adelin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!