简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM