Eight ways to write the singleton mode, very complete!

concept

Singleton mode is an object instance in which only one class exists in the memory of a JVM.

classification

1. Lazy

Create an instance when the class loads

2. Hungry Han Style

Create instances when used

There are other ways to generate singletons, such as double check locks, enumerations, and static internal classes, which are described here.

Lazy-man style

1) Example 1

public class Singleton {  

    private static Singleton instance;  

    private Singleton (){}  

    public static Singleton getInstance() {  
        if (instance == null) {  
            instance = new Singleton();  
        }  
        return instance;  
    }  

}

Thread is not safe and unavailable.

2) Example 2

public class Singleton {  

    private static Singleton instance;  

    private Singleton (){}  

    public static synchronized Singleton getInstance() { 
        if (instance == null) {  
            instance = new Singleton();  
        }  
        return instance;  
    }  

}

Synchronization method, thread-safe, inefficient, not recommended.

3) Example 3

public class Singleton {

    private static Singleton singleton;

	private Singleton() {}

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

}

Threads are insecure, multiple instances are generated, and are not available.

Hungry Han Style

Wireless process security issues can not delay loading, affecting system performance.

4) Example 1

public class Singleton {  

    private static Singleton instance = new Singleton();  

    private Singleton (){}  

    public static Singleton getInstance() {  
		return instance;  
    }  

}

5) Example 2

public class Singleton {  

    private static Singleton instance = null;  

    static {  
		instance = new Singleton();  
    }  

    private Singleton (){}  

    public static Singleton getInstance() {  
		return instance;  
    }  

}

6) Example 3

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;
    }

}

Dual check lock, thread safe, recommended.

7) Example 4

public class Singleton {  

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

    private Singleton (){}  

    public static final Singleton getInstance() {  
		return SingletonHolder.INSTANCE;  
    }  

}

Static internal class, thread-safe, instantiated when called actively, delayed loading efficiency is high, recommended.

8) Example 5

public enum Singleton {  

    INSTANCE;  

    public void whateverMethod() {  

    }  

}

Matters needing attention

1. Consider multithreading

2. Singleton class construction method should be set to private type to prohibit outside 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;  

}

Enumeration types, wireless process security issues, avoiding the creation of new instances by deserializing China, are rarely used.

Use scenarios

1. Tool class objects

2. Classes that can only have one instance in the system

3. Create objects that are frequently or time consuming and frequently used

The following is the application of singleton mode in JDK

In addition, instances in Spring containers default to the single hungry Han type, which instantiates bean s into the container when the container starts, or lazy defalut-lazy-init="true" can be set to delay instantiation and then instantiate them when needed.

Recommend going to my blog to read more:

1.Java JVM, Collections, Multithreaded, New Features Series Tutorial

2.Spring MVC, Spring Boot, Spring Cloud series tutorials

3.Maven, Git, Eclipse, Intellij IDEA Series Tools Tutorial

4.Latest Interview Questions for Java, Backend, Architecture, Alibaba, etc.

Life is good. See you tomorrow~

Tags: Java Spring jvm JDK

Posted on Thu, 26 Mar 2020 21:42:38 -0400 by KSquared