Initialization-on-demand holder Idiom

Source: Internet
Author: User

[Translated from Wikipedia: http://en.wikipedia.org/wiki/initialization_on_deman_holder_idiom]

You may have heard that Singleton has thread security issues. Of course, you can solve this problem through synchronous locking. For more information, see this document.


In software engineering, initialization-on-demand holder refers to the singleton mode of delayed loading. In all Java versions, this method can achieve secure and efficient implementation of high-concurrency delayed initialization.

The code structure is as follows:

 
Public class something {private something () {} Private Static class lazyholder {Private Static final something instance = new something ();} public static something getinstance () {return lazyholder. instance ;}}

This implementation depends on the features in the JVM initialization phase, which are described in the Java language description. When a class is loaded by JVM, the class will go through the initialization process. Since this class does not have other static variables to be initialized, the initialization process will be completed smoothly. The static class lazyholder defined in the class will not be initialized until the JVM determines that lazyholder will be executed. When the static method getinstance is called, the static class lazyholder will be executed. When this happens for the first time, the JVM will load and initialize lazyholder.

Lazyholder initialization causes the static variable instance to be initialized because the external class (that is, lazyholder) executes the private constructor. Because the class initialization process is serialized (guaranteed by the Java language), no parallel synchronization operation is required.

In addition, because the static variable instance is written in the serial operation in the initialization phase, all subsequent concurrent calls to the getinstance method will return the same instance correctly without additional synchronization overhead.

Initialization-on-demand holder Idiom

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.