concept

The singleton pattern means that only one object instance of a class exists in a JVM’s memory.

classification

1. Hungry

The instance is created when the class is loaded

2. Slacker style

The instance is created only when it is used

Of course, there are other ways to generate singletons, such as double check locks, enumerations, and static inner classes, which are covered in this article.

LanHanShi

1) the sample 1

public class Singleton {  

    private static Singleton instance;  

    private Singleton (){}  

    public static Singleton getInstance() {  
        if (instance == null) {  
            instance = new Singleton();  
        }  
        returninstance; }}Copy the code

The thread is unsafe and unavailable.

2) sample 2

public class Singleton {  

    private static Singleton instance;  

    private Singleton (){}  

    public static synchronized Singleton getInstance() { 
        if (instance == null) {  
            instance = new Singleton();  
        }  
        returninstance; }}Copy the code

The synchronization method is not recommended because it is thread safe and inefficient.

3) the sample 3

public class Singleton {

    private static Singleton singleton;

    private Singleton() {}

    public static Singleton getInstance() {
        if(singleton == null) { synchronized (Singleton.class) { singleton = new Singleton(); }}returnsingleton; }}Copy the code

Threads are not safe, creating multiple instances and not available.

The hungry type

There is no thread safety problem, and delayed loading is not allowed, which affects system performance.

4) sample 1

public class Singleton {  

    private static Singleton instance = new Singleton();  

    private Singleton (){}  

    public static Singleton getInstance() {  
        returninstance; }}Copy the code

5) sample 2

public class Singleton {  

    private static Singleton instance = null;  

    static {  
        instance = new Singleton();  
    }  

    private Singleton (){}  

    public static Singleton getInstance() {  
        returninstance; }}Copy the code

6) Double check lock

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(); }}}returnsingleton; }}Copy the code

Double check lock is recommended for thread safety.

7) Static inner class

public class Singleton {  

    private static class SingletonHolder {  
        private static final Singleton INSTANCE = new Singleton();  
    }  

    private Singleton (){}  

    public static final Singleton getInstance() {  
        returnSingletonHolder.INSTANCE; }}Copy the code

Static internal class, thread-safe, active call only instantiation, lazy load efficiency, recommended.

8) enumeration

public enum Singleton {  

    INSTANCE;  

    public void whateverMethod() {}}Copy the code

Matters needing attention

1. Consider multithreading

2, the singleton class constructor should be set to private to prevent external new creation

private Singleton() {}

3. If the class is serializable, consider deserializing to generate multiple instances. The solution is as follows

private Object readResolve() throws ObjectStreamException {

    // instead of the object we're on, return the class variable INSTANCE return INSTANCE; }Copy the code

Enumerated types, with no thread-safety issues, avoid creating new instances of anti-sequence, rarely used.

Usage scenarios

1. Toolclass objects

2. Only one instance of a class can exist in the system

3. Create objects that are frequent or time-consuming and often used

Here’s how the singleton pattern works in the JDK

In addition, instances in the Spring container are singleton types by default, which means that the container instantiates beans into the container at startup. You can also set the lazy defalut-lazy-init=”true” for lazy instantiation and then instantiate them.

Learn more about learning

Need more architecture information and video on cache breakdown, add wechat official account: Java Architect Union

Or scan the QR code to add



Xiaobian will issue articles and technical explanation videos from time to time, thank you