At noon today, I am free to write something about the Java Singleton mode. In fact, there are many ways to implement the singleton mode. Here I will compare and analyze these methods:
First:
[Java]
Public class Singleton2 {
Private Singleton2 (){
System. out. println ("This is Singleton2's instance .");
};
Private static Singleton2 instance = null;
Public static Singleton2 getInstance (){
If (instance = null ){
Instance = new Singleton2 ();
}
Return instance;
}
}
In this case, no lock is applied, and data errors may occur. For example, if two newly generated objects are created at the same time, one changes the object data, and the other uses the previous one.
Second:
[Java]
Public class Singleton1 {
Private Singleton1 (){
System. out. println ("This is Singleton1's instance .");
}
Private static Singleton1 instance = null;
Public static Singleton1 getInstance2 (){
If (instance = null) {// 1
Synchronized (Singleton1.class) {// 2
If (instance = null ){
Instance = new Singleton1 ();
}
}
}
Return instance;
}
}
This will only cause blocking at the first time, and every time an object is attached to the instance, it will jump in step 3. During the first instance, blocking will occur in step 3, it won't happen in the future. This is relatively the best.
Third:
[Java]
Public class Singleton1 {
Private Singleton1 (){
System. out. println ("This is Singleton1's instance .");
}
Private static Singleton1 instance = null;
Public static synchronized Singleton1 getInstance () {// 1
If (instance = null ){
Instance = new Singleton1 ();
}
Return instance;
}
}
When multithreading occurs, blocking occurs every time in 1.