Singleton mode in java
Singleton mode: instances with only one object in the context.
Application Scenario: Only one scenario is required for a thread pool, cache, and other systems.
Three Common Singleton modes:
1. Delayed Loading
public class Singleton { private static Singleton uniqueInstance; private Singleton() {} public static Singleton getInstance() { if (uniqueInstance == null) uniqueInstance = new Singleton(); return uniqueInstance; }}
You can call the static method of the class to obtain it:
Singleton singleton = Singleton. getInstance ();
Problem: multi-thread synchronization
Multiple Threads may execute if (uniqueInstance = null) judgment at the same time when an object is generated for the first time, so that multiple new instances can be created at the same time.
Improvement:
public class SynSingleton { private static SynSingleton uniqueInstance; private SynSingleton() {} public static synchronized SynSingleton getInstance() { if (uniqueInstance == null) uniqueInstance = new SynSingleton(); return uniqueInstance; }}
In this way, synchronization is implemented through synchronized code blocks.
2. Eager instantiation
The preceding method requires synchronization of synchronized every time an object is obtained, with a high overhead. The synchronization operation is only valid for the first time new (no new operation is performed for each subsequent call, it is equivalent to read-only but not write). Therefore, you can create a new object when the class is loaded, and then do not perform the new operation. The improvement is as follows:
public class UrgSingleton { private static UrgSingleton uniqueInstance = new UrgSingleton(); private UrgSingleton() {} public static UrgSingleton getInstance() { return uniqueInstance; }}
The advantages and disadvantages of delayed instantiation and eager instantiation are also obvious:
If this object has a high overhead and is not used in the whole process, the instantiated object will consume resources in vain.
The synchronization of delayed instantiation has a high overhead, so the following dual-check locking method is available.
3. Double check and lock
public class DoubleSynSingleton { private static volatile DouleSynSingleton uniqueInstance; private DoubleSynSingleton() {} public static DoubleSynSingleton getInstance() { if (uniqueInstance == null) { synchronized(DoubleSynSingleton.class) { if(uniqueInstance == null) uniqueInstance = new DoubleSynSingleton(); } } return uniqueInstance; }}
As shown above, the synchronized method is used only when a new object is created for the first time. After obtaining the object instance, if (uniqueInstance = null) of the outer layer is determined, the system exits and does not use subsequent synchronization code blocks. In this way, the performance is improved.