6

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?

RonK
  • 9,472
  • 8
  • 51
  • 87

3 Answers3

7

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());
    }
});
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Indeed. `ThreadLocal` allows N threads to have N independent variables -- it may not relate to the objects contained at all (there is no requirement that each ThreadLocal has a different and/or unique object). –  Jun 26 '11 at 07:02
0

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

irreputable
  • 44,725
  • 9
  • 65
  • 93
  • this is not correct. There are sound use-cases where the object in a thread local is shared by multiple threads. – Stephen C Jun 26 '11 at 08:05
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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216