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?
Thread Safety With the exception of Dispose(), all public and protected members of ThreadLocal<T> are thread-safe and may be used concurrently from multiple threads.
Java ThreadLocal is used to create thread local variables. We know that all threads of an Object share it's variables, so the variable is not thread safe. We can use synchronization for thread safety but if we want to avoid synchronization, we can use ThreadLocal variables.
ThreadLocal s should be stored in static variables to avoid memory leaks. If a ThreadLocal is stored in an instance (non-static) variable, there will be M \* N instances of the ThreadLocal value where M is the number of threads, and N is the number of instances of the containing class.
Most common use of thread local is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object using synchronized keyword/block. Instead, give each thread its own instance of the object to work with.
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());
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With