Reputation: 9652
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?
Upvotes: 6
Views: 261
Reputation: 718798
In addition to what @aioobe said, consider the case of InheritableThreadLocal
, in which the value of local is passed from a thread to each child thread that it creates.
And as @pst says, there is nothing to prevent the same value being used in different (non-inheritable) ThreadLocal
s.
In short, you have to do a thorough analysis of the thread locals, the way that they are initialized and the way that they are used before you can safely conclude that they don't need to be threadsafe.
Upvotes: 0
Reputation: 45433
Either he used ThreadLocal
wrongly, or ConcurrentHashMap
wrongly. The likelihood that the combination makes sense is close to 0.
Upvotes: 0
Reputation: 420991
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());
}
});
Upvotes: 7