Search code examples
javaconcurrencythread-local

Is there any benefit in puting a ThreadSafe object on a ThreadLocal?


I recently saw a piece of code which used a ThreadLocal object and kept a ConcurrentHashMap within it.

Is there any logic/benefit in this, or is it redundant?


Solution

  • If the only reference to the concurrent hashmap resides in the ThreadLocal, the hashmap is obviously only referenced from a single thread. In such case I would say it is completely redundant.

    However, it's not hard to imagine someone "sharing" the thread-locally stored hashmap with other threads:

    ThreadLocal<ConcurrentHashMap<String, String>> tl = ...
    
    // ...
    
    final ConcurrentHashMap<String, String> props = tl.get();
    
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            props.add(key.getText(), val.getText());
        }
    });