Singleton design pattern

1, Basic introduction to singleton mode

The so-called class singleton design pattern is to take certain methods to ensure that there can only be one object instance for a class in the whole software system, and the class only provides a method to obtain its object instance (static method).

2, There are eight ways of singleton mode

  • Hungry Han formula (static constant)
  • Hungry Chinese (static code block)
  • Lazy (thread unsafe)
  • Lazy (thread safety, synchronization method)
  • Lazy (thread safe, synchronous code block)
  • duplication check
  • Static inner class
  • enumeration

3, Implementation of singleton mode

1. Hungry Han formula (static constant)

//Hungry Han formula (static variable)
class Singleton {
	
	//1. The constructor is privatized, and the external energy is new
	private Singleton() {
	}
	//2. Create object instances within this class
	private final static Singleton instance = new Singleton();
	
	//3. Provide a public static method to return the instance object
	public static Singleton getInstance() {
		return instance;
	}
}

Description of advantages and disadvantages

  • Advantages: this method is relatively simple, that is, instantiation is completed when the class is loaded. Thread synchronization problems are avoided.
  • Disadvantages: the instantiation is completed when the class is loaded, which does not achieve the effect of Lazy Loading. If this instance is never used from beginning to end, it will cause a waste of memory
  • This method is based on the classloder mechanism to avoid the synchronization problem of multiple threads. However, instance is instantiated when class loading. In the singleton mode, most of them call getInstance methods, but there are many reasons for class loading. Therefore, it is uncertain that other methods (or other static methods) cause class loading, At this time, initializing instance does not achieve the effect of lazy loading

Conclusion: This singleton mode is available, which may cause a waste of memory

2. Hungry Chinese style (static code block)

//Hungry Han formula (static variable)
class Singleton {
	//1. The constructor is privatized, and the external energy is new
	private Singleton() {
	}
	//2. Create object instances within this class
	private  static Singleton instance;
	
	static { // In a static code block, create a singleton object
		instance = new Singleton();
	}
	//3. Provide a public static method to return the instance object
	public static Singleton getInstance() {
		return instance;
	}
}

Description of advantages and disadvantages

  • This method is actually similar to the above method, except that the class instantiation process is placed in the static code block. When the class is loaded, the code in the static code block is executed to initialize the class instance. The advantages and disadvantages are the same as above.

Conclusion: This singleton mode is available, but it may cause memory waste

3. Lazy (thread unsafe)

//Lazy (thread unsafe)
class Singleton {
	private static Singleton instance;
	
	private Singleton() {}
	
	//Provide a static public method. Create an instance only when the method is used
	//Lazy style
	public static Singleton getInstance() {
		if(instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}

Description of advantages and disadvantages

  • It has the effect of Lazy Loading, but it can only be used under single thread.
  • If, under multithreading, one thread enters the if (singleton == null) judgment statement block and has not yet had time to execute, and another thread also passes the judgment statement, multiple instances will be generated. Therefore, this method cannot be used in a multithreaded environment

Conclusion: do not use this method in actual development

4. Lazy (thread safety, synchronization method)

// Lazy (thread safety, synchronization method)
class Singleton {
	private static Singleton instance;
	
	private Singleton() {}
	
	//Provide a static public method, add synchronous processing code, and solve thread safety problems
	//Lazy style
	public static synchronized Singleton getInstance() {
		if(instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}

Description of advantages and disadvantages

  • Solves thread safety issues
  • The efficiency is too low. When each thread wants to obtain an instance of a class, it must synchronize the getInstance() method. In fact, this method only executes the instantiation code once. If you want to obtain this class instance later, just return it directly. Method is too inefficient to synchronize

Conclusion: this method is not recommended in practical development

5. Lazy (thread unsafe, synchronous code block)

// Lazy (thread unsafe, synchronous code block)
class Singleton {
	private static Singleton singleton;

	private Singleton() {}

	//Provide a static public method, add synchronous processing code, and solve thread safety problems
	//Lazy style
	public static Singleton getInstance() {
		if(singleton == null){
			synchronized (Singleton.class){
				singleton = new Singleton();
			}
		}
		return singleton;
	}
}

Conclusion: not recommended

6. Double check

// Lazy (thread safety, synchronization method)
class Singleton {
	private static volatile Singleton instance;
	
	private Singleton() {}
	
	//Provide a static public method, add double check code, solve thread safety problems, and solve lazy loading problems at the same time
	//At the same time, it ensures the efficiency and is recommended to use
	
	public static Singleton getInstance() {
		if(instance == null) {
			synchronized (Singleton.class) {
				if(instance == null) {
					instance = new Singleton();
				}
			}
		}
		return instance;
	}
}

Description of advantages and disadvantages

  • The concept of double check is often used in multithreading development. As shown in the code, we have conducted two if (singleton == null) checks to ensure thread safety.
  • In this way, the instantiated code is executed only once. When accessing again later, judge if (singleton == null) and return the instantiated object directly to avoid repeated method synchronization
  • Thread safety; Delayed loading; High efficiency

Conclusion: this single case design pattern is recommended in practical development

7. Static internal class

// The static internal class is completed, which is recommended
class Singleton {
	private static volatile Singleton instance;
	
	//Constructor privatization
	private Singleton() {}
	
	//Write a static inner class with a static attribute Singleton
	private static class SingletonInstance {
		private static final Singleton INSTANCE = new Singleton(); 
	}
	
	//Provide a static public method and directly return SingletonInstance.INSTANCE
	
	public static Singleton getInstance() {
		
		return SingletonInstance.INSTANCE;
	}
}

Description of advantages and disadvantages

  • This method adopts the mechanism of class loading to ensure that there is only one thread when initializing the instance.
  • The static internal class method will not be instantiated immediately when the Singleton class is loaded. Instead, when instantiation is required, the SingletonInstance class will be loaded by calling the getInstance method, so as to complete the instantiation of Singleton.
  • The static properties of the class will only be initialized when the class is loaded for the first time. Therefore, the JVM helps us ensure the safety of threads. When the class is initialized, other threads cannot enter.
  • Advantages: thread insecurity is avoided, delayed loading is realized by using the characteristics of static internal classes, and the efficiency is high

Conclusion: it is recommended to use

8. Enumeration

//Using enumeration, you can implement singleton. It is recommended
enum Singleton {
	INSTANCE; //attribute
	public void sayOK() {
		System.out.println("ok~");
	}
}

Description of advantages and disadvantages

  • This implements the singleton pattern with the help of enumerations added in JDK 1.5. It can not only avoid the problem of multi-threaded synchronization, but also prevent deserialization and re creation of new objects.
  • This approach is advocated by Josh Bloch, author of Effective Java

Conclusion: it is recommended to use

4, Source code analysis of singleton pattern in JDK application

In JDK, java.lang.Runtime is a classic singleton pattern (hungry Chinese style)

5, Notes and details of singleton mode

  • The singleton mode ensures that there is only one object of this class in the system memory, saving system resources. For some objects that need to be created and destroyed frequently, using the singleton mode can improve the system performance
  • When you want to instantiate a singleton class, you must remember to use the corresponding method to get the object, not new
  • Scenarios for using singleton mode: objects that need to be created and destroyed frequently, objects that take too much time or resources to create objects (i.e. heavyweight objects), but are often used, tool objects, and objects that frequently access databases or files (such as data sources, session factories, etc.)

Keywords: Java Design Pattern Back-end

Added by bough on Sun, 24 Oct 2021 10:20:38 +0300