Is there any use in setting a ThreadSafe object to ThreadLocal?

I recently saw a piece of code that used a ThreadLocal object and contained a ConcurrentHashMap inside it.

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

+6
source share
3 answers

If the only link to the parallel hash file is in ThreadLocal , the hash map obviously refers to only one thread. In that case, I would say that it is completely redundant.

However, it is easy to imagine that someone is "sharing" a locally stored hash file with other streams:

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

Either he used ThreadLocal incorrectly, or ConcurrentHashMap erroneously. The probability that the combination makes sense is close to 0.

0
source

In addition to what @aioobe said, consider the InheritableThreadLocal case, in which the local value is passed from the thread to each child thread that it creates.

And as @pst says, there is nothing to prevent the use of the same value in different (non-inherited) ThreadLocal s.

In short, you need to conduct a thorough analysis of the flow locales, how to initialize them, and how to use them before you can safely conclude that they should not be thread safe.

0
source

Source: https://habr.com/ru/post/891376/


All Articles