[Go] How to correctly write a singleton pattern

Source: Internet
Author: User

Do you really know a single case?

These two days in the "Art of multi-processor programming" (English version) refers to the lazy single-case pattern of the non-tightness of the writing. I would like to comb the details of the problem in the case of the singleton pattern. So I found an article:

Original address: http://wuchong.me/blog/2014/08/28/how-to-correctly-write-singleton-pattern/

PDF: here

Points:

1. Optimize performance with double-check lock [lazy-type]

2. Use volatile to avoid the "double check lock" in the command reflow. And only takes effect after 1.5 [lazy type]

3. A hungry man type private static final Singleton instance = new Singleton (); Thread Safety

4. Static internal class static nested class notation:

 Public classSingleton {Private Static classSingletonholder {Private Static FinalSingleton INSTANCE =NewSingleton (); }      PrivateSingleton () {} Public Static FinalSingleton getinstance () {returnsingletonholder.instance; }  }

5. The wording of the enum

 Public enum easysingleton{    INSTANCE;}

"There is no need to worry about double checked locking, but also to prevent deserialization from causing new objects to be recreated"

-------------------------------------------------

Cause thinking. How is spring's singleton bean created? Cond

[Go] How to correctly write 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.