Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 231
RonK Avatar asked Jun 26 '11 06:06

RonK


People also ask

Is ThreadLocal thread-safe?

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.

Are ThreadLocal variables thread-safe?

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.

Does ThreadLocal need to be static?

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.

Should we use ThreadLocal?

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.


1 Answers

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());
    }
});
like image 185
aioobe Avatar answered Sep 21 '22 14:09

aioobe