Java - ThreadLocal vs ConcurrentHashMap

concurrency, concurrenthashmap, java, thread-local

Solution

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.

Problem

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?

Original source