简体   繁体   中英

Regarding static holder singleton pattern

I have developed singleton in many ways depending upon the condition like volatile/lazy singleton, eager singleton, normal singleton and through Enum also, but specifically I want to know about static holder pattern singleton shown below.

public static class Singleton {
    private static class InstanceHolder {
        public static Singleton instance = new Singleton();
    }

    private Singleton(){}

    public static Singleton getInstance() { 
        return InstanceHolder.instance;
    }
}

Please advise under which conditions it is beneficial and what are its benefits.

This pattern is beneficial for at least 3 reasons:

  1. Static factory
  2. Lazy initialization
  3. Thread safe

The JVM defers initializing the InstanceHolder class until it is actually used, and because the Singleton is initialized with a static initializer, no additional synchronization is needed. The first call to getInstance by any thread causes InstanceHolder to be loaded and initialized, at which time the initialization of the Singleton happens through the static initializer.

Static holder pattern is also considered as the smartest replace for Double-check-locking antipattern.

This is a way to make a thread-safe lazy singleton by exploiting the way how JVM loads classes. You can read more about why and how to correctly implement it in Bloch's Effective Java book.

Remember, that from the testable code point of view singletons (and global state in general) are not beneficial and should be avoided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM