catalogue
Introduction to single example design mode
Eight ways of single case design mode
Hungry Han formula (static constant)
Hungry Chinese (static code block)
Lazy (thread safety, synchronization method)
Lazy (thread safe, synchronous code block)
Source code analysis of singleton pattern in JDK application
Notes and details of singleton mode
Singleton design pattern
Introduction to single example design 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).
For example, Hibernate's SessionFactory acts as a proxy for the data storage source and is responsible for creating the Session object. SessionFactory is not lightweight. Generally, only one SessionFactory is required for a project, which will use the singleton mode.
Eight ways of single case design mode
The singleton mode has eight modes:
1) Hungry Han formula (static constant)
2) Hungry Chinese (static code block)
3) Lazy (thread unsafe)
4) Lazy (thread safety, synchronization method)
5) Lazy (thread safe, synchronous code block)
6) Double check
7) Static inner class
8) Enumeration
Hungry Han formula (static constant)
Application example of hungry Han formula (static constant)
The steps are as follows:
1) Constructor Privatization (prevent new)
2) Class
3) Expose a static public method. getInstance
4) Code implementation
public class SingletonTest01 { public static void main(String[] args) { //test Singleton instance = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); System.out.println(instance == instance2); // true System.out.println("instance.hashCode=" + instance.hashCode()); System.out.println("instance2.hashCode=" + instance2.hashCode()); } } //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; } }
Advantages and disadvantages Description:
1) Advantages: this method is relatively simple, that is, instantiation is completed when the class is loaded. Thread synchronization problems are avoided.
2) 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
3) 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
4) Conclusion: This singleton mode is available, which may cause a waste of memory
Hungry Chinese (static code block)
code demonstration:
public class SingletonTest02 { public static void main(String[] args) { //test Singleton instance = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); System.out.println(instance == instance2); // true System.out.println("instance.hashCode=" + instance.hashCode()); System.out.println("instance2.hashCode=" + instance2.hashCode()); } }
//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; } }
Advantages and disadvantages Description:
1) This method is actually similar to the above method, except that the class instantiation process is placed in the static code block, which is executed when the class is loaded
Line the code in the static code block to initialize the instance of the class. The advantages and disadvantages are the same as above.
2) Conclusion: This singleton mode is available, but it may cause memory waste
Lazy (thread unsafe)
code demonstration:
public class SingletonTest03 { public static void main(String[] args) { System.out.println("Lazy 1, thread unsafe~"); Singleton instance = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); System.out.println(instance == instance2); // true System.out.println("instance.hashCode=" + instance.hashCode()); System.out.println("instance2.hashCode=" + instance2.hashCode()); } } 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; } }
Advantages and disadvantages Description:
1) It has the effect of Lazy Loading, but it can only be used under single thread.
2) If one thread enters the if (singleton == null) judgment statement block under multithreading and has not had time to execute, the other thread also passes
When this judgment statement is, multiple instances will be generated. Therefore, this method cannot be used in a multithreaded environment
3) Conclusion: do not use this method in actual development
Lazy (thread safety, synchronization method)
code demonstration:
public class SingletonTest04 { public static void main(String[] args) { System.out.println("Lazy 2, thread safe~"); Singleton instance = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); System.out.println(instance == instance2); // true System.out.println("instance.hashCode=" + instance.hashCode()); System.out.println("instance2.hashCode=" + instance2.hashCode()); } } // 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; } }
Advantages and disadvantages Description:
1) Solves thread safety issues
2) 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
One instantiation of the code is enough. If you want to get an instance of this class, just return. Method is too inefficient to synchronize
3) Conclusion: this method is not recommended in practical development
Lazy (thread safe, synchronous code block)
public class SingletonTest06 { public static void main(String[] args) { System.out.println("duplication check"); Singleton instance = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); System.out.println(instance == instance2); // true System.out.println("instance.hashCode=" + instance.hashCode()); System.out.println("instance2.hashCode=" + instance2.hashCode()); } } // 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 synchronized Singleton getInstance() { if(instance == null) { synchronized (Singleton.class) { if(instance == null) { instance = new Singleton(); } } } return instance; } }
Advantages and disadvantages Description:
1) 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.
2) 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
3) Thread safety; Delayed loading; High efficiency
4) Conclusion: this single case design pattern is recommended in practical development
Static inner class
code demonstration:
public class SingletonTest07 { public static void main(String[] args) { System.out.println("Using static inner classes to complete singleton mode"); Singleton instance = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); System.out.println(instance == instance2); // true System.out.println("instance.hashCode=" + instance.hashCode()); System.out.println("instance2.hashCode=" + instance2.hashCode()); } } // 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 synchronized Singleton getInstance() { return SingletonInstance.INSTANCE; } }
Advantages and disadvantages Description:
1) This method adopts the mechanism of class loading to ensure that there is only one thread when initializing the instance.
2) 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.
3) 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.
4) Advantages: thread insecurity is avoided, delayed loading is realized by using the characteristics of static internal classes, and the efficiency is high
5) Conclusion: it is recommended to use
enumeration
Code demonstration
public class SingletonTest08 { public static void main(String[] args) { Singleton instance = Singleton.INSTANCE; Singleton instance2 = Singleton.INSTANCE; System.out.println(instance == instance2); System.out.println(instance.hashCode()); System.out.println(instance2.hashCode()); instance.sayOK(); } } //Using enumeration, you can implement singleton. It is recommended enum Singleton { INSTANCE; //attribute public void sayOK() { System.out.println("ok~"); } }
Advantages and disadvantages Description:
1) This is done with the help of jdk1 5 to implement the singleton mode. It can not only avoid the problem of multi-threaded synchronization, but also prevent deserialization and re creation of new objects.
2) This approach is advocated by Josh Bloch, author of Effective Java
3) Conclusion: it is recommended to use
Source code analysis of singleton pattern in JDK application
Source code analysis of singleton pattern in JDK application
1) In our JDK, Java Lang. runtime is the classic singleton mode (hungry Chinese style)
2) Code analysis + Debug source code + code description
Notes and details of singleton mode
1) 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
2) When you want to instantiate a singleton class, you must remember to use the corresponding method to get the object, not new
3) 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.)