Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - ThreadLocal vs ConcurrentHashMap

I have a very simple question regarding a performance difference between ThreadLocal and ConcurrentHashMap. In some places in my code I need to maintain a mapping from a Thread to some Object, which has to be thread safe. One option is to use ConcurrentHashMap and one is to use ThreadLocal. Any advantages/disadvantages for either of these approaches, mostly in terms of speed?

like image 946
Bober02 Avatar asked Feb 19 '14 15:02

Bober02


People also ask

When should I use ThreadLocal?

Java ThreadLocal is used to create thread local variables. We know that all threads of an Object share it's variables, so the variable is not thread safe. We can use synchronization for thread safety but if we want to avoid synchronization, we can use ThreadLocal variables.

Which is better HashMap or ConcurrentHashMap?

HashMap performance is relatively high because it is non-synchronized in nature and any number of threads can perform simultaneously. But ConcurrentHashMap performance is low sometimes because sometimes Threads are required to wait on ConcurrentHashMap.

Is ThreadLocal slow?

Rust thread-locals are slower than they could be. This is because they violate zero-cost abstraction principle, specifically the “you don't pay for what you don't use bit”. Rust's thread-local implementation( 1, 2 ) comes with built-in support for laziness — thread locals are initialized on the first access.

Is ConcurrentHashMap thread-safe in Java?

ConcurrentHashMap class is thread-safe i.e. multiple threads can operate on a single object without any complications. At a time any number of threads are applicable for a read operation without locking the ConcurrentHashMap object which is not there in HashMap.


1 Answers

This is definitely a case for ThreadLocal.

ThreadLocal values are stored in the Thread object, rather than in a concurrent map, so there is absolutely no locking involved, and is therefore much more efficient. Also note that values attached to the thread through a ThreadLocal are automatically discarded when the thread dies, which won't happen with ConcurrentHashMap.

One last thing, though: if you have threads that are "reused" in some way, such as workers kept in a pool, you should most probably clear the ThreadLocal's value before returning the thread to the pool. Otherwise, you may leak one task's context into the next task, which might pose either performance, correctness or security issues.

like image 99
jwatkins Avatar answered Oct 05 '22 17:10

jwatkins