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 ?
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.
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