Double-checked mode (DCL)
The advantage of DCL is high resource utilization. The singleton is instantiated only when getInstance is executed for the first time. The disadvantage is that the reaction of the first load is slightly slower, and there are certain defects in high concurrency environment, although the probability of occurrence is very small.
public class Singleton {
private volatile static Singleton instance;
private Singleton (a){}public static Singleton getInstance(a) {
if (instance== null) {
synchronized (Singleton.class) {
if (instance== null) {
instance= newSingleton(); }}}returnsingleton; }}Copy the code
Static inner class
Instance is not initialized the first time the Singleton class is loaded, only the first time the getInstance() method is called, the virtual machine loads the SingletonHolder class and initializes instance.
This method not only ensures thread-safety, singleton uniqueness, but also delays the initialization of the singleton. It is recommended to use this method to implement the singleton pattern.
public class Singleton {
private Singleton(a){}public static Singleton getInstance(a){
return SingletonHolder.sInstance;
}
private static class SingletonHolder {
private static final Singleton sInstance = newSingleton(); }}Copy the code
Enumerated the singleton
Thread safety, high call efficiency, can not delay loading
public enum Singleton {
INSTANCE;
public void doSomeThing(a) {}}Copy the code
Use containers to implement the singleton pattern
It reduces the user’s use cost, also hides the specific implementation from the user, and reduces the coupling degree
public class SingletonManager { privatestatic Map<String.Object> objMap = new HashMap<String.Object> (); privateSingleton(){ } publicstatic void registerService(String key, Objectinstance){if(! Objmap.containskey (key) {objmap.put (key, instance); } } publicstatic ObjectgetService(String key){returnObjMap. Get (key); }}Copy the code
reference
Seven ways to write a singleton pattern