Design pattern creation - singleton pattern

Keywords: Programming jvm JDK Session Java

As a common design pattern, singleton pattern is not repeated here.

There are nine ways to implement singleton mode, but some of them are defective. In summary, there are four types:

1, Starved Han model

/**
 * @ClassName: Singleton2
 * @description: Singleton mode - starved mode (thread safe, but not resource efficient)
 * @author: edison_Kwok
 * @Date: create in 2019/12/10 22:59
 * @Version: 1.0
 */
public class Singleton2 {

    private static Singleton2 uniqueSingleton2 = new Singleton2();

    private Singleton2() {
    }

    public static Singleton2 getUniqueSingleton2() {
        //Thread insecurity is mainly due to the fact that uniqueInstance has been instantiated many times. If uniqueInstance is instantiated directly, thread insecurity will not occur.
        //But the way of direct instantiation also loses the benefit of resource saving brought by delayed instantiation.
        return uniqueSingleton2;
    }
}

2, Double check lazy mode

/**
 * @ClassName: Singleton4
 * @description: Singleton mode -- lazy mode (double check lock thread safety)
 * @author: edison_Kwok
 * @Date: create in 2019/12/10 23:09
 * @Version: 1.0
 */
public class Singleton4 {

    //It is also necessary to decorate uniqueInstance with volatile keyword. uniqueInstance = new Singleton(); this code is actually executed in three steps:
    //
    //Allocate memory space for uniqueInstance
    //Initialize uniqueInstance
    //Point uniqueInstance to the allocated memory address

    //Using volatile can prevent the instruction rearrangement of JVM and ensure the normal operation in multithreaded environment.
    private volatile static Singleton4 uniqueSingleton4;

    private Singleton4() {
    }

    //uniqueInstance only needs to be instantiated once, and then it can be used directly.
    // The lock operation only needs to be performed on the instantiated part of the code. Only when the uniqueInstance is not instantiated can the lock be performed.
    //Double check lock first determines whether the uniqueInstance has been instantiated. If it has not been instantiated, then lock the instantiation statement.
    public static Singleton4 getUniqueSingleton4() {
        if (uniqueSingleton4 == null) {
            synchronized (Singleton4.class) {
                if (uniqueSingleton4 == null) {
                    //If the null judgment is not added, two threads may be waiting
                    //Both threads execute the new command
                    uniqueSingleton4 = new Singleton4();
                }
            }
        }
        return uniqueSingleton4;
    }
}

3, Inner class

/**
 * @ClassName: Singleton5
 * @description: Static inner class implementation
 * @author: edison_Kwok
 * @Date: create in 2019/12/10 23:18
 * @Version: 1.0
 */
public class Singleton5 {

    private Singleton5() {
    }

    //When the Singleton class is loaded, the static inner class SingletonHolder is not loaded into memory.
    private static class Singleton5Holder {
        //SingletonHolder will only be loaded if the getUniqueInstance() method is called to trigger SingletonHolder.INSTANCE
        // At this point, the INSTANCE is initialized, and the JVM can ensure that the INSTANCE is instantiated only once.
        private static final Singleton5 uniqueSingleton5 = new Singleton5();
    }

    public static Singleton5 getUniqueSingleton5() {
        //This method not only has the advantage of delayed initialization, but also provides thread safety support by JVM.
        return Singleton5Holder.uniqueSingleton5;
    }
}

4, Enumeration form (recommended by the big guy)

/**
 * @ClassName: Singleton6
 * @description:
 * @author: edison_Kwok
 * @Date: create in 2019/12/22 20:32
 * @Version: 1.0
 */
public enum Singleton6 {
    instance;
}

class Client{
    public static void main(String[] args) {
        Singleton6 instance = Singleton6.instance;
    }
}

5, Notes and details of singleton mode

    1. The singleton mode ensures that there is only one object in the system memory and saves the internal resources of the system. For some objects that need to be created and destroyed frequently, the singleton mode can improve the system performance;
    1. When you want to instantiate a singleton class, you must remember to get the corresponding method to get the object, not new;
    1. Singleton mode usage scenario: objects that need to be repeatedly and frequently destroyed. When creating objects, it takes too much time and resources (i.e. heavyweight objects), but frequently used objects, tool class objects, frequent template databases or file objects (such as data sources, session factories, etc.).

6, Single instance mode in JDK source code

java.lang.Runtime class in jdk

Posted by phpnewbie911 on Sun, 22 Dec 2019 06:11:59 -0800