1 Overview
The singleton pattern has several benefits:
(1) Certain classes are created more frequently. For some large objects, this is a huge system overhead.
(2) The new operator is omitted, which reduces the frequency of system memory usage and reduces GC pressure.
(3) Some classes, such as the core trading engine of an exchange, control the transaction process. If multiple classes can be created, the system will be completely messed up.
2 Detailed explanation
There are two commonly used ways of writing the singleton pattern as follows.
2.1 Hungry Chinese style
If the application always creates and uses the singleton pattern, or if the creation and runtime pressure is not very high, you can use a private static variable to create the object in advance.
Copy the code code as follows:
package org.scott.singleton;
/**
* @author Scott
* @version 2013-11-16
* @description
*/
public class Singleton1 {
private static Singleton1 uniqueInstance = new Singleton1();
private Singleton1(){
}
public static Singleton1 getInstance(){
return uniqueInstance;
}
}
In this case, when the JVM loads this class, the object will have been created according to the initialization sequence. At the same time, the JVM can guarantee that any thread must create this instance first and only once before accessing this singleton object.
Of course, you can also use a static inner class to accomplish the same function.
Copy the code code as follows:
package org.scott.singleton;
/**
* @author Scott
* @version 2013-11-16
* @description
*/
public class Singleton2 {
private Singleton2() {
}
/**
* An internal class is used here to maintain the singleton
* */
private static class SingletonFactory {
private static Singleton2 instance = new Singleton2();
}
public static Singleton2 getInstance() {
return SingletonFactory.instance;
}
/**
* If the object is used for serialization, it can be guaranteed that the object remains consistent before and after serialization
* */
public Object readResolve() {
return getInstance();
}
}
2.2 Double lock method
"Double lock", as the name suggests, is two locks. The first lock is used to check whether the instance object to be created has been created. If it has not been created, the second lock is used for synchronization.
Copy the code code as follows:
package org.scott.singleton;
/**
* @author Scott
* @version 2013-11-16
* @description
*/
public class Singleton3 {
private volatile static Singleton3 uniqueInstance;
private Singleton3(){
}
public static Singleton3 getInstance(){
if(uniqueInstance == null){
synchronized(Singleton3.class){
if(uniqueInstance == null){
uniqueInstance = new Singleton3();
}
}
}
return uniqueInstance;
}
}
If the performance requirements are relatively high, this method can greatly reduce the creation time. Currently, this method is also a relatively common way to create singletons.