What you should know about the singleton pattern

Posted by Torleif on Tue, 03 Dec 2019 03:38:29 +0100

Singleton mode

Usage scenario:

  • Hibernate only needs one SessionFactory
  • In Spring, if scope="singleton" is specified, the bean will be singleton (default singleton is not specified). Business logic component, DAO component and data source component are singleton, because they do not need to save the user's state
  • The data connection pool uses a single instance mode without creating multiple

Advantages:

  • Reduce the overhead of creating objects
  • Easy to manage the lifecycle of a single object

Writing:

  • Lazy Loading, i.e. when to use and when to initialize, need to consider thread synchronization
  • Starved Chinese style, that is, instantiation is completed when the class is loaded, avoiding thread synchronization

First: starving Chinese style, thread safety

public class Singleton {

    private final static Singleton INSTANCE = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
        return INSTANCE;
    }
}

The second type: lazy, unsafe thread, can only be used under single thread

public class Singleton {

    private static Singleton singleton;

    private Singleton() {}

    public static Singleton getInstance() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                singleton = new Singleton();
            }
        }
        return singleton;
    }
}

Third: lazy, double check, thread safety

public class Singleton {

    private static volatile Singleton singleton;

    private Singleton() {}

    public static Singleton getInstance() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

Fourth: ThreadLocal, thread safe

public class Manager {

    private static final ThreadLocal<Manager> sManager = new ThreadLocal<Manager>() {
        @Override
        protected Manager initialValue() {
            return new Manager();
        }
    };

    private Manager() {

    }

    public static Manager getInstance() {
        return sManager.get();
    }
}

Topics: Hibernate Spring