Singleton Pattern in Java

The singleton pattern means that a class can only be instantiated once and is used to represent a global or system-wide component. It is often used for logging, factories, platform component management, etc. The singleton pattern looks simple but is actually very difficult.

The singleton itself has a variety of implementation methods. Generally speaking, it can be divided into two types: lazy mode and hungry mode. The lazy mode is relatively simple.

public class FooSingleton {
    public final static FooSingleton INSTANCE = new FooSingleton();
    private FooSingleton() { }
    public void bar() { }
}

The private constructor is called when the building is initialized and only called once, and the JVM guarantees that it will not be called by other threads after the class is fully initialized.

There are three common implementations of thread safety in hungry mode:

  1. Double detection locking mode, note that the new FooSingleton() operation in Java actually consists of three atomic operations of allocating instance memory, referring to the memory address, and initializing the instance. In addition to double locking, the instance instance must be defined as a volatile type to prevent instruction rearrangement to ensure complete accuracy.
  2. Static inner class methods, the inner class is only loaded when its static methods, variables, etc. are called.
    public class FooSingleton4 {
        private FooSingleton4() {
        }
        public static FooSingleton4 getInstance() {
            return FooSingleton4Holder.INSTANCE;
        }
        private static class FooSingleton4Holder {
            private static final FooSingleton4 INSTANCE = new FooSingleton4();
        }
    }
  3. Using enumeration, according to Java Language Specification 8.9, "Enum's final clone method ensures that the enumeration can never be cloned, and its special serialization mechanism ensures that the copied object cannot be deserialized. At the same time, it is also forbidden to use reflection to perform enumeration. Instantiation. These four aspects are guaranteed, and there will be no other enumeration instances of the same kind outside the enumeration constants."
    public  enum FooEnumSingleton {
        INSTANCE;
        public static FooEnumSingleton getInstance() { return INSTANCE; }
        public void bar() { }
    }

    In order to truly implement a singleton and prevent multiple instances from appearing, it is also necessary to consider that the singleton cannot be cloned through the clone method, cannot be copied through serialization and deserialization, and cannot be reserialized through reflection. Now it is generally recommended to use the singleton writing method, which is not only concise in code, but can also better prevent the above problems.

http://www.importnew.com/16995.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325163960&siteId=291194637