Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advice on using ThreadLocals to wrap mutable singleton objects

From Java Concurrency in practice Chapter 3.3.3. ThreadLocal

Thread-local variables are often used to prevent sharing in designs based on mutable Singletons or global variables.

If we wrap the mutable Singleton guy in a ThreadLocal each thread will have its own copy of the Singleton ? How will it remain a singleton then ? Is this what the authors meant or am I missing something pretty obvious here ?

like image 662
Geek Avatar asked Feb 09 '13 09:02

Geek


1 Answers

If we wrap the mutable Singleton guy in a ThreadLocal

AFAIK you do not wrap the singleton class with ThreadLocal, but the object contained within the singleton which is mutable or non-thread safe. As the example discusses correctly that the JDBC Connection is not thread safe and will require additional protection, which in turn increases contention.

So in the cases when the Singletons are used just for the purpose of sharing, then replacing those things with ThreadLocal is a good idea, as all the threads have their own Connection and no more added protection is required.

Other good example of use case of ThreadLocal is Random generation, if there is a single Random object then there is contention within threads for the "seed", so if each thread has its own Random object then there is no contention any more and that makes sense.

like image 135
Narendra Pathai Avatar answered Oct 26 '22 08:10

Narendra Pathai