Singleton实现中的按需初始化习惯用语与简单静态初始化器 [英] Initialize-On-Demand idiom vs simple static initializer in Singleton implementation

查看:197
本文介绍了Singleton实现中的按需初始化习惯用语与简单静态初始化器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用静态初始化实现线程安全单例时,是否确实需要按需初始化惯用法?还是简单的实例静态声明就足够了?

Is the Initialize-On-Demand idiom really necessary when implementing a thread safe singleton using static initialization, or would a simple static declaration of the instance suffice?

将实例简单声明为静态字段:

Simple declaration of instance as static field:

class Singleton
{
 private static Singleton instance=new Singleton();

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

vs

class Singleton {
   static class SingletonHolder {
      static final Singleton INSTANCE = new Singleton();
   }

   private Singleton () {..}

   public static Singleton getInstance() {
      return SingletonHolder.INSTANCE;
   }
}

我之所以这样问,是因为Brian Goetz建议本文采用第一种方法:

I ask this because Brian Goetz recommends the 1st approach in this article:

http://www.ibm.com/developerworks/java/library/j-dcl/index.html

他在本文中建议后者

http://www.ibm.com/developerworks/library/j-jtp03304/

后一种方法是否提供前者没有的任何好处?

Does the latter approach provide any benefits that the former doesn't?

推荐答案

第一种方法是,一旦加载Singleton类,就会创建单例.另一方面,一旦调用getInstance()方法,它将被创建.在调用getInstance之前,Singleton类可能有很多加载原因.因此,您很可能会在实际使用它时更早地对其进行初始化,这违背了延迟初始化的目的.是否需要延迟初始化是一个单独的故事.

In first approach your singleton will get created once you load Singleton class. In the other, it will get created once you call getInstance() method. Singleton class may have many reasons to get loaded before you call getInstance. So you will most likely initialize it much earlier when you actually use it and that defeats the purpose of lazy initialization. Whether you need lazy initialization is a separate story.

这篇关于Singleton实现中的按需初始化习惯用语与简单静态初始化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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