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.
Example 1 - By using static reference of ThreadLocal
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.
Example 2 - By using generic factory pattern
Step 1 : Create the singleton class
Step 2 : Create the interface
Step 3 : Create the generic ThreadLocalFactory utility class
Now create the generic ThreadLocalFactory which can convert any Factory to a ThreadLocal scope.
Step 4 : Create a singleton factory
Step 4 : Push the singleton factory to the thread local scope
We are done. Now we have created a Thread local singleton factory, which will return unique instance per thread.
Lets write the test method now.
Now lets run the test method -
This clearly demonstrates creation of unique objects per thread.