Four ways to get a single case

Source: Internet
Author: User

A singleton pattern is often used in the project, which summarizes

1-A Hungry man

 Public class Singleton  {    // a hungry man type    Private Singleton () {            }    privatestaticnew  Singleton ();      Public Static Singleton getinstance () {        return  Singleton;    }    }

2 Lazy Thread-safe

 Public classSingleton {//Lazy Type    PrivateSingleton () {}Private StaticSingleton Singleton =NULL;  Public Static synchronizedSingleton getinstance () {if(singleton==NULL){            return NewSingleton (); }        returnSingleton; }}

3 Two-Lieutenant, thread-safe.

 Public classSingleton {//double check     PrivateSingleton () {}Private Static volatileSingleton Singleton =NULL;  Public StaticSingleton getinstance () {if(singleton==NULL){             synchronized(Singleton.class){                 if(singleton==NULL) {                    return NewSingleton (); }             }         }        returnSingleton; }}

4 static internal classes are nested class thread-safe

 Public class Singleton {        private  Singleton () {}        privatestaticclass  instanceholder{        privatestaticnew  Singleton ();    }     publicstatic  Singleton getinstance () {        return  Instanceholder.singleton;}    }

Synchronized will affect service performance, why it will affect, not too clear, later understand in the supplement. Static inner classes (nested classes) are better in comparison

Four ways to get a single case

Related Article

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.