A discussion of the syntax and thread safety of a singleton pattern

Source: Internet
Author: User

A hungry man mode: Singleton mode, that is, no matter when used, when the class is loaded to instantiate an object of this class
And then wait until you use the same instance object
Benefits: Using this approach in a multi-threaded environment, you can avoid the conflicts caused by multithreading. In response, lazy mode (on-demand instantiation)
Class Singleton1{private Singleton1 () {}private static Singleton1 S1 = new Singleton1 ();p ublic static Singleton1 Getsingle ton () {return s1;}}

Lazy Mode: Single-case mode,
Benefit: Initialize the instance object until it is used, avoiding wasted memory
Cons: You'll encounter thread safety issues
Class Singleton2{private Singleton2 () {}private static Singleton2 s2 = null;public static Singleton2 GetSingleton2 () {if ( S2 = = null) {s2 = new Singleton2 ();} return s2;}}

Registration mode: With the help of an inner class, a lazy singleton, because the Java mechanism stipulates that
The inner class Singletonholder is loaded only when the getinstance () method is first called (lazy is implemented),
and its loading process is thread-safe, so this pattern overcomes the drawbacks of lazy and a hungry man patterns

Class Singleton3{private Singleton3 () {}private static class Singleholder{private final static Singleton3 s3 = new Singleto N3 ();} public static Singleton3 GetSingleton3 () {return singleholder.s3;}}

Common locking solves the thread safety problem of Singleton mode
Analysis: Although thread safety issues are resolved, each thread calls getinstance to lock,
We want to add locks only when we call getinstance for the first time, we need to improve

Class Singleton4{private static Singleton4 s4= null;private Singleton4 () {}public static synchronized Singleton4 GetSingleton4 () {if (S4 = = null) {s4 = new Singleton4 ();} return S4;}}

A discussion of the syntax and thread safety of a singleton 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.