This is the 31st day of my participation in the August More Text Challenge
We continue with our previous article, “Challenging the singleton pattern (7),” which looked at the most elegant implementation of singletons, called enum enum implementations. With nearly all of the singleton patterns covered, this article has added an additional look at how to implement thread-wide singletons.
TheadLocal thread singleton
All we have talked about in the previous articles are global singletons, and there are many special scenarios where thread-scoped singletons are used, such as storing authorization tokens, and so on. ThreadLocal is inherently thread-safe.
ThreadLocal is a class that creates thread-local variables. Normally, we create variables that can be accessed and modified by any thread. Variables created using ThreadLocal can only be accessed by the current thread and cannot be accessed or modified by other threads.
The code is implemented as follows.
public class SingletonInThreadLocal { private SingletonInThreadLocal (){ } private static final ThreadLocal<SingletonInThreadLocal> threadLocalInstance = new ThreadLocal<SingletonInThreadLocal>(){ @Override protected SingletonInThreadLocal initialValue() { return new SingletonInThreadLocal(); }}; public static SingletonInThreadLocal getInstance(){ return threadLocalInstance.get(); }}Copy the code
The code is simple: when ThreadLocal is initialized, it sets the initial value of the ThreadLocal wrap, which is the instance object of the singleton. External applications that getInstance objects are accessed through the getInstance static method.
How about writing a test method to see if we can achieve thread-level singletons?
public static void main(String[] args) {
System.out.println(SingletonInThreadLocal.getInstance());
System.out.println(SingletonInThreadLocal.getInstance());
new Thread(()-> System.out.println(SingletonInThreadLocal.getInstance())).start();
new Thread(()-> System.out.println(SingletonInThreadLocal.getInstance())).start();
}
Copy the code
First we get the instance object twice in the main thread, and then we open up two child threads to get the instance object. The result is as follows.
It is clear that a thread-level singleton has indeed been achieved. In the singleton we implemented above, to ensure thread safety, we control by locking mechanism. ThreadLocal is implemented by placing all objects in a ThreadLocalMap, providing one object for each thread, and implementing a space-for-time policy to isolate threads.
Xi. Conclusion
The singleton pattern is the entry level of the design pattern. It looks simple, but there are many potholes. This article analyzes various implementations and application scenarios. If you’re interested, you can do it all, and test how efficient it is to create objects.