Java Singleton pattern implementation (thread safe)

Source: Internet
Author: User

1  PackageCom.javaee.corejava;2 /**3 * Thread-safe single-case mode4  * @authorMIAOYF5  *6  */7  Public classSingleton {8     /**9 * private static constant single-instance objectTen * Volatile: One * used in multi-threading, synchronous variables. thread to improve efficiency, a member variable (such as a) is copied a copy (such as B), A * The access to a in the thread is actually B.  - * Synchronization of A and B is performed only in certain actions. Thus there is a and B inconsistency. Volatile is used to avoid this situation.  - * Volatile tells the JVM that the variable it modifies does not keep the copy and accesses the main memory directly (that is, a above) the      */ -     Private Static volatileSingleton instance=NULL; -     /** - * Privatization of constructors to prevent initialization by constructor functions +      */ -     PrivateSingleton () { +          A     } at     /** - * Returns a singleton example -      */ -      Public StaticSingleton getinstance () { -         if(instance==NULL){ -             synchronized(Singleton.class) { in                 if(instance==NULL){ -Instance=NewSingleton (); to                 } +             } -         } the         returninstance; *     } $}

Java Singleton pattern implementation (thread safe)

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.