开发者

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

开发者 https://www.devze.com 2023-03-15 22:36 出处:网络
I recently saw a piece of code which used a ThreadLocal object and kept a ConcurrentHashMap within it.

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 re开发者_JAVA技巧dundant?


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());
    }
});


Either he used ThreadLocal wrongly, or ConcurrentHashMap wrongly. The likelihood that the combination makes sense is close to 0.


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) ThreadLocals.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消