Design Mode-singleton Mode
Singleton Pattern
Only one instance exists in the class, that is, only one object can be created. Some Classes create multiple objects, which may lead to many problems, such as abnormal program behavior, excessive resource usage, or inconsistent results. The single-piece mode is often used to manage shared resources, such as database connections or thread pools.
Brief definition: The single-piece mode ensures that a class has only one instance and provides a global access point.
Implementation of single-piece Mode
The single-piece mode is implemented throughPrivate ConstructorThe class containsStatic MethodGetInstance (). You can call this method to create and return a unique object. It may also return a created object.
Analysis: in the single-piece mode, you must first restrict the creation of objects from the outside, so that the constructor can be called only within the class by declaring the constructor as private. How to call this constructor? To use this class without objects of this class, a static method is required. This method calls a private constructor and returns a unique single-piece object.
Analysis of the implementation of the classic single-piece Mode
The implementation of the classic single-piece mode is as follows:
public class Singleton { private static Singleton singleton = null; private Singleton() { } public static Singleton getInstance() { if(singleton== null) { singleton=newSingleton(); } return singleton; }}This implementation method has problems. In the case of multiple threads, multiple objects may be created.
We can add the synchionized keyword to the getInstance method to force each thread to wait for other processes to exit the method before entering this method.
public class Singleton { private static Singleton singleton = null; private Singleton() { } public static synchionized Singleton getInstance() { if(singleton== null) { singleton=newSingleton(); } return singleton; }Such synchronization may cause performance problems. There are two ways to improve the performance:
1. Use "eager" to create an instance without delaying instantiation:
public class Singleton {private static Singleton uniqueInstance = new Singleton(); private Singleton() {} public static Singleton getInstance() {return uniqueInstance;}}Using this method, we rely on JVM to create a unique single-piece instance immediately when loading this class. JVM ensures that this instance must be created before any thread accesses the uniqueInstance static variable.
If we want him to be created only when I first get instance. In this way, we can control the real time when the class is created, rather than entrusting the class creation to the class loader. It can be implemented in the following versions:
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = newSingleton(); } privateSingleton (){} public static final Singleton getInstance() { return SingletonHolder.INSTANCE; }}The above method still uses the JVM mechanism to ensure thread security. Because SingletonHolder is private, there is no way to access it except getInstance (), so it is only available in getInstance () it is created only when it is called. It is not synchronized when the instance is read, and has no performance defects. It does not depend on the JDK version.
2. Use "double check lock" to reduce synchronization in getInstance:
First, check whether the instance has been created. If the instance has not been created, synchronize the instance.
public class Singleton {private volatile static Singleton uniqueInstance; private Singleton() {} public static Singleton getInstance() {if (uniqueInstance == null) {synchronized (Singleton.class) {if (uniqueInstance == null) {uniqueInstance = new Singleton();}}}return uniqueInstance;}}
VolatileWhen the uniqueInstance variable is initialized to a Singleton instance, multiple threads correctly process the uniqueInstance variable.
We need to declare singleton as volatile because: singleton= new Singleton()This sentence is not an atomic operation. In fact, the following three things are done in JVM.
Allocate memory to singleton and call the Singleton constructor to initialize the member variables to form an instance pointing the singleton object to the allocated memory space (this step is not null after singleton is executed)
However, optimization of Command Re-sorting exists in the JVM instant compiler. That is to say, the order of the second and third steps is not guaranteed. The final execution order may be 1-2-3 or 1-3-2. If it is the latter, it will be preempted by thread 2 before 3 is finished and 2 is not executed. At this time, the instance is not null (but it is not initialized ), therefore, thread 2 will directly return the instance and then use it. Then, an error is automatically reported.