Multi-threaded Singleton Design Mode

Source: Internet
Author: User
I have no other hands, but I am familiar with it! Multi-threaded Singleton Design Mode

As we all know, in singleton mode, constructor is private and calls constructor internally through static methods to return instance objects of this class. The common code is as follows:

?
12345678910 public
class
Singleton {    private
static Singleton singletonObj; 
    private
Singleton(){}       public
static Singleton getInstance(){        if(singletonObj ==
null){            singletonObj =
new Singleton();        }        return
singletonObj;    }}

  

In the case of a single thread, there is indeed only one instance, but in the case of multiple threads, unexpected situations will occur.

Create a testsingleton class as follows:

?
public
class
TestSingleton implements
Runnable {     private
Singleton s = null;         public
Singleton getS() {        return
s;    }     public
void setS(Singleton s) {        this.s = s;    }     public
static void
main(String[] args) {
        TestSingleton ts1 =
new TestSingleton();        TestSingleton ts2 =
new TestSingleton();        Thread t1 =
new Thread(ts1);        Thread t2 =
new Thread(ts2);        t1.start();        t2.start();                 Singleton s1 = ts1.getS();        Singleton s2 = ts2.getS();                 System.out.println(s1 == s2);    }     @Override    public
void run() {                 s = Singleton.getInstance();    }}

  

The running result returns false.

In a multi-threaded environment, you need to consider the synchronization problem and modify the code in the singleton mode as follows:

?
public
static
Singleton getInstance() {         if
(singletonObj == null) {            synchronized
(Singleton.class) {                if
(singletonObj == null) {                    singletonObj =
new Singleton();                }            }        }        return
singletonObj;    }

  

Re-run testsingleton and return the result "true" to ensure that the singleton mode is correct even in a multi-threaded environment.

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.