Reputation: 510
When should one prefer ThreadLocal
over synchronization, apart from for the performance improvement? Please explain using a real life example.
Upvotes: 4
Views: 3735
Reputation: 27115
ThreadLocal
is not an alternative to synchronized
. The main problem solved by ThreadLocal
is how to manage per-thread static
data in an application.
static
is something that you should try to avoid whenever you can: It's a recipe for un-testable, brittle code.
Upvotes: 3
Reputation: 18941
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.
Upvotes: 3
Reputation: 69
ThreadLocal provides global variable access with in a Thread. This will help when you want to share a variable across methods and still retain Thread scope.
J2EE application servers use ThreadLocal for tracking Transaction, Security context with out passing around
Upvotes: 0
Reputation: 533442
The only reason to use Threads is for performance reasons (or perhaps you like confusion ;).
AFAICS If you discount performance, there is not reason to use Threads, ThreadLocal nor synchronzied.
Upvotes: 0