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.
source
share