Comparison of several methods for implementing the singleton pattern

I am a novice, learning for the first time, and I feel that I have understood it. If there is any inadequacy or misunderstanding, please correct me.

April 12 , 2018 _ _

10:13

Points to Note

    1. A private static variable

    2. A private constructor

    3. A public static method

·         Ordinary constructor

package singleton;

public class CommonSingleton {
	private static CommonSingleton instance;//A static variable
	private CommonSingleton() { // a private constructor
	}
	public static CommonSingleton getSingleton(){//A static method
		if(instance==null){
			instance=new CommonSingleton();
		}
		return instance;
	}
}


Constructors with         synchronized locks

1. Because multi-threaded concurrent access may cause the created instance to be not single (this problem is only caused when the instance is first created), the function of the synchronization lock is to allow only one thread to access the method at a time, ensuring that A singleton is created, but since the instance is created only once, the synchronization lock works every time it is accessed, so it also greatly limits the execution efficiency of multi-threading and reduces performance.

package singleton;

public class SynchronizedSingleton {
	private static SynchronizedSingleton instance;
	private SynchronizedSingleton() {
	}
	public static synchronized SynchronizedSingleton getSingleton(){
		if(instance==null){   
			instance=new SynchronizedSingleton();
		}
		return instance;
	}
}

·         Initial creation

The instance is created immediately when the jvm loads this class. The advantage is that it solves the problem that multiple threads may repeatedly create instances, but this increases the burden of the application initialization process (suitable for programs that need to be initialized without heavy burden)

package singleton;

public class InitSingleton {
	private static InitSingleton instance=new InitSingleton();
	private InitSingleton () {
	}
	public static InitSingleton getSingleton(){
		return instance;
	}
	
}

double -         checked locks

This is a suitable solution to solve the problem that multi-threaded access may lead to repeated creation of singletons, but also does not want to directly lock (resulting in reduced performance during concurrency), and also occupies system initialization resources during initialization.

package singleton;

public class DoubleCheckSingleton {
	private volatile static DoubleCheckSingleton instance;
	private DoubleCheckSingleton() {
	}
	public static DoubleCheckSingleton getSingleton(){
		if(instance==null){
			synchronized (DoubleCheckSingleton.class) {
				if(instance==null){
					instance=new DoubleCheckSingleton();
				}
			}
		}
		return instance;
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325578375&siteId=291194637