Java design pattern--to solve the lazy thread safety problem in the single-case design pattern

Source: Internet
Author: User

First write a singleton, lazy mode:

 Public class Singledemo {    privatestaticnull;     Private Singledemo () {}      Public Static   Singledemo getinstance () {        ifnull) {            new Singledemo ();        }         return s;    }}


Write a test class:

 Public class ThreadDemo3 {        publicstaticvoid  main (string[] args) {        =  Singledemo.getinstance ();         = singledemo.getinstance ();         = = s2);}    }


The running result is always true, stating that there is no problem with a single thread, and the following is a multi-thread access to the singleton

 Public class Implements Runnable {    // Store Singleton object, use set to not hold duplicate element public    new hashset< Singledemo>();    @Override    publicvoid  run () {        // get a singleton        Singledemo s = singledemo.getinstance ();         // Add a single case         Singles.add (s);    }}


Using multiple threads for concurrent access to a single example:

 Public classThreadDemo3 { Public Static voidMain (string[] args) {//Singledemo S1 = singledemo.getinstance ();//Singledemo s2 = singledemo.getinstance ();//System.out.println (s2 = = s2);ThreadTest T =Newthreadtest (); NewThread (t). Start (); NewThread (t). Start (); NewThread (t). Start (); NewThread (t). Start (); NewThread (t). Start (); NewThread (t). Start (); NewThread (t). Start (); NewThread (t). Start ();    System.out.println (T.singles); }}

The results of the operation are as follows:

[[Email protected], [email protected]]

Or

[[email protected]]

Describes thread concurrency access security issues, not all of which are the same instance

How to solve the thread safety problem?

Of course, the sync lock mechanism is used.

The following improvements to the single example:

 Public class Singledemo {    privatestaticnull;     Private Singledemo () {}      Public Static synchronized Singledemo getinstance () {        ifnull) {            new  Singledemo ();        }         return s;    }}

Thread safety resolves after adding a sync function

Run multiple times to get the same instance without 2 instances

[[email protected]]

However, in the case of multi-threaded concurrent access, each thread to obtain an instance to determine the lock, efficiency is low, in order to improve efficiency, I added a double-judge method, solve the problem of efficiency

The code is as follows;

 Public classSingledemo {Private StaticSingledemo s =NULL; PrivateSingledemo () {} Public StaticSingledemo getinstance () {/*if the first thread obtains an instance object of the singleton, the subsequent thread does not need to enter the synchronization code block when it acquires the instance .*/        if(s = =NULL){            //the lock used for synchronizing code blocks is a singleton bytecode file object and can only be used with this lock            synchronized(Singledemo.class){                if(s = =NULL) {s=NewSingledemo (); }            }        }        returns; }}

In this way to solve the lazy-type thread safety problems, but also improve efficiency, but in the actual development or use a hungry man-style comparison, after all, this code is more, more cumbersome.

Java design pattern--to solve the lazy thread safety problem in the single-case design pattern

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.