java 关于静态持有人单例模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15019306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:13:59  来源:igfitidea点击:

Regarding static holder singleton pattern

java

提问by user2094103

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.

我已经以多种方式开发了单例,具体取决于 volatile/lazy 单例、急切单例、普通单例和通过 Enum 等条件,但特别是我想了解下面显示的静态持有者模式单例。

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.

请告知在哪些条件下它是有益的,它的好处是什么。

回答by Vladimir Kishlaly

This pattern is beneficial for at least 3 reasons:

这种模式至少有以下三个好处:

  1. Static factory
  2. Lazy initialization
  3. Thread safe
  1. 静态工厂
  2. 延迟初始化
  3. 线程安全

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 getInstanceby any thread causes InstanceHolder to be loaded and initialized, at which time the initialization of the Singleton happens through the static initializer.

JVM 会推迟初始化 InstanceHolder 类,直到它被实际使用,并且因为 Singleton 是使用静态初始化器初始化的,所以不需要额外的同步。任何线程对getInstance的第一次调用都会导致 InstanceHolder 被加载和初始化,此时 Singleton 的初始化通过静态初始化程序发生。

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

静态持有者模式也被认为是双重检查锁定反模式的最聪明的替代品。

回答by denis.solonenko

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.

这是一种通过利用 JVM 加载类的方式来制作线程安全的惰性单例的方法。您可以在 Bloch 的 Effective Java 书中详细了解为什么以及如何正确实现它。

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

请记住,从testable code单例(以及一般的全局状态)的角度来看,这是没有好处的,应该避免。