维基百科的单例模式实现 [英] Singleton pattern implementation from Wikipedia

查看:162
本文介绍了维基百科的单例模式实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是指 Bill Pugh的Singleton模式解决方案a>在维基百科上:

I am referring to the solution for the Singleton Pattern by Bill Pugh on Wikipedia:

public class Singleton
{

    // Private constructor prevents instantiation from other classes

    private Singleton() {}

     /**
    * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
    * or the first access to SingletonHolder.INSTANCE, not before.
    */

    private static class SingletonHolder 
    { 

        private static final Singleton INSTANCE = new Singleton();
    }

   public static Singleton getInstance()
   {

       return SingletonHolder.INSTANCE;
   }

}

他们提到: p>

Here they have mentioned:


内部类没有更早引用(并且因此在类加载器之前不被加载)比 getInstance( )被调用。因此,该解决方案是线程安全的,而不需要特殊的语言结构(即 volatile synchronized

The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized).

但是,没有可能的2线程将调用 getInstance()同一时间,这将导致创造两个单例的实例?在这里使用 synchronized 是不是安全?如果是,应该在代码中使用哪一个?

However, isn't there a possibility that 2 threads would call getInstance() at the same time, which would lead to two instances of singleton being created? Isn't it safe to use synchronized here? If yes, where should it be used in the code?

推荐答案

请参阅工作原理,在同一部分链接的文章初始化请求持有人成语中。

See the "How it works", in the article "Initialization on demand holder idiom" linked from the same section.

简而言之,首次调用 getInstance()时会发生什么:

In a nutshell, here's what happens when you call getInstance() the first time:


  1. JVM看到对 SingletonHolder 的引用,它从未见过。

  2. 执行是暂停,而初始化 SingletonHolder 。这包括运行任何静态初始化,包括单例实例。

  3. 执行恢复。任何其他线程调用 getInstance()同时会看到 SingletonHolder 已被初始化。 Java规范保证类初始化是线程安全的。

  1. The JVM sees a reference to SingletonHolder it has never seen referenced before.
  2. Execution is paused while it initializes SingletonHolder. This includes running any static initialization, which includes the singleton instance.
  3. Execution resumes. Any other threads calling getInstance() at the same time will see that SingletonHolder is already initialized. The Java spec guarantees that class initialization is thread-safe.

这篇关于维基百科的单例模式实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆