A brief introduction to single mode

This paper introduces the singleton pattern with java code to implement demo. The content is for reference only. Please point out the shortcomings in time and welcome to exchange and discuss.

Singleton mode

Singleton pattern is a kind of creation pattern, which ensures that a singleton class has only one instance object.

Singleton mode features

There are many ways to implement singleton pattern, but it follows three characteristics.

  • A singleton class can have only one instance object.

  • The instance object can only be built by the singleton class itself.

  • The singleton class must provide the instance object to other objects.

Slacker type

public class SingletonDemo {

    private static SingletonDemo instance;

    private SingletonDemo() {

    }

    public static synchronized SingletonDemo getInstance() {

        if (null == instance) {
            instance = new SingletonDemo();
        }
        return instance;
    }
}

Time for space, lazy loading and synchronized decoration ensure multithreading safety, but also reduce efficiency.

Hungry man

public class SingletonDemo {

    private static SingletonDemo instance = new SingletonDemo();

    private SingletonDemo() {

    }

    public static SingletonDemo getInstance() {
        return instance;
    }
}

Space for time, non lazy loading, through the class loading mechanism to ensure thread safety, without using synchronized, the efficiency is relatively higher.

DCL: double checked locking

public class SingletonDemo {

    private volatile static SingletonDemo instance;

    private SingletonDemo() {

    }

    public static SingletonDemo getInstance() {

        if (null == instance) {

            synchronized (SingletonDemo.class) {
                if (null == instance) {
                    // Because the operation is non atomic, it needs to be modified by volatile
                    instance = new SingletonDemo();
                }
            }
        }
        return instance;
    }
}

Time for space, lazy load, synchronize from getInstance to the corresponding single instance operation, which ensures the safety of multiple threads and improves the efficiency compared with lazy type.

Static inner class

public class SingletonDemo {

    private static class SingletonDemoHolder {
        private static final SingletonDemo instance = new SingletonDemo();
    }

    private SingletonDemo() {

    }

    public static final SingletonDemo getInstance() {
        return SingletonDemoHolder.instance;
    }
}

Time for space, lazy loading. By introducing static internal classes, it avoids the instance initialization caused by SingletonDemo loading, realizes lazy loading, and improves the performance compared with double check locking.

Keywords: Java

Added by drak on Mon, 30 Dec 2019 20:56:57 +0200