Java - ThreadLocal vs ConcurrentHashMap

I have a very simple question regarding the difference in performance between ThreadLocaland ConcurrentHashMap. In some places in my code, I need to maintain matching from Threadto some Object, which should be thread safe. One option is to use ConcurrentHashMap, and one is to use ThreadLocal. Any advantages / disadvantages for any of these approaches, mainly in terms of speed?

+4
source share
1 answer

This is definitely the case for ThreadLocal.

ThreadLocal values ​​are stored in the Thread object, and not in the parallel map, so locking is absolutely not required and, therefore, much more efficient. Also note that values ​​attached to the thread through ThreadLocal are automatically deleted when the thread dies, which will not happen with ConcurrentHashMap.

And finally: if you have threads that are somehow "reused", for example, workers are stored in the pool, you should probably clear the ThreadLocal value before returning the thread to the pool. Otherwise, you can insert one task context into the next task, which can cause problems with performance, correctness, or security.

+8
source

Source: https://habr.com/ru/post/1527729/


All Articles