How to create singleton instance per thread in java
16 Oct 2016
In case you are new to the term singleton design pattern, It is recommended that, you read this article before proceeding further.
By this time I assume you know the basics and usefulness of a singleton design pattern.
Sometimes we endup in a situation where we can not use the singleton classes in a multiple threaded application. This could be for sevaral reasons like, making use of some data or some instance which are not thread-safe (eg. HashMap).
To create singleton instance per thread, we can make use of a ThreadLocal instance (java doc).
When we invoke get() on a ThreadLocal instance, it returns an independently initialized copy of the variable for each thread. ThreadLocal instances are typically private static fields in classes which we wish to make singleton per thread.
Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are garbage colelcted.
Now lets create the test method. Here we will print the instance hashcode with the thread name, so that we can conclude which instance is bound for a thread.
Run the test case -
This clearly shows, it is creating a unique instance per thread.