Hungry mode is also called preloading mode. It directly creates and initializes a singleton object when the class is loaded, so it does not have thread safety issues. It relies on the ClassLoader class mechanism and is only loaded once when the program starts, so there is no thread safety issue. Its implementation code is as follows:
public class Singleton { // 1.防止外部直接 new 对象破坏单例模式 private Singleton() {} // 2.通过私有变量保存单例对象 private static Singleton instance = new Singleton(); // 3.提供公共获取单例对象的方法 public static Singleton getInstance() { return instance; } }
Advantages: Implementation Simple and no thread safety issues. Disadvantages: The object is created when the class is loaded. If it is not used after creation, it will cause a waste of resources.
Lazy mode and hungry mode are exactly the opposite. The so-called lazy mode is lazy loading (delayed loading), which means that it is loaded only for the first time. It will be initialized only when used.
Its implementation code is as follows:
public class Singleton { // 1.防止外部直接 new 对象破坏单例模式 private Singleton() {} // 2.通过私有变量保存单例对象 private static volatile Singleton instance = null; // 3.提供公共获取单例对象的方法 public static Singleton getInstance() { if (instance == null) { // 第一次效验 synchronized (Singleton.class) { if (instance == null) { // 第二次效验 instance = new Singleton(); } } } return instance; } }
The lazy mode uses double validation locks and volatile to ensure thread safety. ’s , as can be seen from the above code, whether it is hungry man mode or lazy man mode, their implementation steps are the same:
Create a private constructor to prevent The new object is used directly in other calling places, so that the object created is not a singleton object.
Create a private variable to save the singleton object.
Provide a public method to return a singleton object.
Compared with the hungry mode, the lazy mode will not cause a waste of resources, but the writing method is more complicated.
Static inner class can ensure both thread safety and lazy loading. It will only pass the ClassLoader mechanism when it is called. to load and initialize the internal static class, so it is thread-safe. The implementation code of this mode is as follows:
public class Singleton { // 1.防止外部直接 new 对象破坏单例模式 private Singleton() { } // 2.静态内部类 private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } // 3.提供公共获取单例对象的方法 public static final Singleton getInstance() { return SingletonHolder.INSTANCE; } }
The enumeration is also used for the first time It will be loaded and initialized by the Java virtual machine when used, so it is also thread-safe and lazy-loaded. Its implementation code is as follows:
public enum EnumSingleton { INSTANCE; public EnumSingleton getInstance(){ return INSTANCE; } }
The above is the detailed content of Implementation methods and common writing methods of Java singleton pattern. For more information, please follow other related articles on the PHP Chinese website!