Java Singleton Mode Analysis

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.