Summary of Java Singleton patterns

Source: Internet
Author: User

The implementation of the Singleton mode is summarized as follows:

The first way: the method of obtaining the instance synchronously, multithreading security, lazy mode. Initialize at the moment the instance is invoked.

 Public classSingleton1 {Private StaticSingleton1 instance =NULL; PrivateSingleton1 () {} Public Static synchronizedSingleton1 getinstance () {if(Instance = =NULL) {instance=NewSingleton1 (); }        returninstance; }}

The first way: a hungry man mode, thread-safe, but slow loading. The object information was initialized at the moment the class was loaded.

 Public class Singleton2 {    //  class Loads the moment it creates a unique instance    privatestaticnew Singleton2 ();     Private Singleton2 () {    }    publicstatic  Singleton2 getinstance () {         return  instance;}    }

The Third way: Double check lock mode, only at the time of the first creation of the mutual exclusion check, empty to create the object.

 Public classSingleton3 {//the use of volatile after JDK 1.5 to initialize the instance ensures that multithreading is handled correctly    Private Static volatileSingleton3 instance =NULL; PrivateSingleton3 () {} Public StaticSingleton3 getinstance () {if(Instance = =NULL) {            synchronized(Singleton3.class) {                if(Instance = =NULL) {instance=NewSingleton3 (); }            }        }        returninstance; }}

Summary of Java Singleton patterns

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.