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?
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.
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.
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.
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.
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.
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