1 overview
The single example pattern has several benefits:
(1) Some classes are created more frequently, and for some large objects, this is a large system overhead.
(2) eliminates the new operator, reduces the system memory usage frequency, reduces the GC pressure.
(3) Some classes, such as the core trading engine of the exchange, control the transaction flow, if the class can create multiple words, the system is completely chaotic.
2 detailed
A single example pattern is often written in two ways.
2.1 A Hungry man type
If your application always creates and uses a single case pattern, or if the pressure is not high at creation and runtime, you can use a private static variable to create the object in advance.
Copy 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 so doing, when the JVM loads the class, the object is created in the order of initialization. At the same time, the JVM can guarantee that any thread must create this instance first and only once before accessing the singleton object.
Of course, you can also use a static inner class to accomplish the same function.
Copy Code code as follows:
Package Org.scott.singleton;
/**
* @author Scott
* @version 2013-11-16
* @description
*/
public class Singleton2 {
Private Singleton2 () {
}
/**
* Use an internal class here to maintain a single example
* */
private Static Class Singletonfactory {
private static Singleton2 instance = new Singleton2 ();
}
public static Singleton2 getinstance () {
return singletonfactory.instance;
}
/**
* If the object is used for serialization, you can ensure that the object remains consistent before and after serialization
* */
Public Object Readresolve () {
return getinstance ();
}
}
2.2 Double Lock mode
"Double lock", as the name implies is two locks, the first lock to check whether the instance object to create has been created, if not yet created before using a second lock to synchronize.
Copy 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 high, this approach can significantly reduce the time to create, and for now, this is a more common way to create a single case.