[Java] [Singleton] [DCL]

Source: Internet
Author: User
Tags volatile

Singleton
    • There can be only one instance; You must create your own instance; this instance must be provided to all other objects
Implementation method A hungry man type singleton
    • Pre-loading method
    • Class Single {  private single () {    System.out.println ("OK");  }    private static Single Instance = new single ();    public static single getinstance () {    return instance;  }}
    • Advantages:
      • Thread safe
      • Fast call time (good one static object created when class is loaded)
    • Disadvantages:
      • Resource utilization is low (may not be required by the system)
      • cannot be used in some scenarios. For example, when creating a dependent parameter or configuration file for a single instance.
Lazy-Singleton
    • lazy Load method
    •  
    • applies to a single-threaded environment, and the Not Trhead-safe,getinstance () method may return two different instances. The
    • can be changed to the Thread-safe version, as follows:
      public class        Lazysingleton {private static Lazysingleton instance; Private Lazysingleton () {} public static synchronized Lazysingleton getinstance () {if (instance = = nul           L) {instance = new Lazysingleton ();                                          } return instance; }} 
    • Pros: Do not perform getinstance pairs will not be instantiated
    • disadvantage: The response is not fast when loading for the first time. Each call to getinstance The synchronization cost is large . (lots of unnecessary synchronizations)
DCL Singleton
    • Double Check Lock
    • Avoid synchronizing every time the GetInstance method is called
    • public class Lazysingleton {  private static Lazysingleton instance;  Private Lazysingleton () {} public    static Lazysingleton getinstance () {    if (instance = = null) {      synchronized ( Lazysingleton.class) {        if (instance = = null) {          instance = new Lazysingleton ();}}    }    return instance;}  }
    • The first layer of judgment avoids unnecessary synchronization. The second layer of judgment is to create the instance in the case of thread safety.
    • Advantages: High resource utilization and high efficiency under multi-thread.
    • Disadvantage: The first load reaction is not fast, due to some reasons Java memory model occasionally fail, in high concurrency has a certain flaw.
    • The code above still has an unsafe security :
      Instance = new Lazysingleton () This statement is not actually an atomic operation, it probably consists of three things:
      1. Allocating memory to instances of Lazysingleton;
      2. Initializes the Lazysingleton () constructor;
      3. Point the instance object to the allocated memory space ( instance becomes non-null at the time of this step).

However , because the Java compiler allows the processor to be executed in order (order reordering), the sequence of 2 and 3 points above is not guaranteed . (meaning that it may instance! = NULL when it is possible that the constructor is not actually initialized).
The workaround is to define instance as volatile . (Volatile has two semantics: 1. Guarantee the visibility of variables; 2. Prohibit reordering of instructions for this variable)

    • Refer to <<java concurrent programming >> P286 ~ P287. In subsequent versions of JMM (>= Java5.0), the DCL can be initiated in a way that combines volatile, and this approach has a minimal impact on performance. However, the use of the DCL has been widely discarded.
    • (Because the semantics of the volatile masking command reordering are fully fixed in JDK1.5, the previous JDK still does not completely avoid the problem caused by reordering even if the variable is declared volatile, mainly because the code before and after the volatile variable still has a reorder problem.) )
Static Inner class Singleton
    • Class Single {  private ' {} ' private    static class Instanceholder {    private static final single instance = new single ();  }    public static single getinstance () {    return instanceholder.instance ();}  }
    • Advantages: Thread safety, high resource utilization.
    • Disadvantage: The reaction is unpleasant when loading for the first time.
    • Principle: Class-level inner classes (member inner classes of static adornments) are loaded only when they are first used .
Summary
    • In view of the efficiency, safety and other problems, generally used a hungry man type singleton or static internal class singleton. The latter is a common method of singleton implementation.

[Java] [Singleton] [DCL]

Related Article

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.