`
zhangle
  • 浏览: 25968 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

Java的singleton模式的double-check问题

    博客分类:
  • Java
阅读更多
以下是double-checked locking的java代码:
public class Singleton {
    private Singleton instance = null;
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized(this) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}


但double-check在J2SE 1.4或早期版本在多线程或者JVM调优时由于out-of-order writes,是不可用的。

这个问题在J2SE 5.0中已经被修复,可以使用volatile关键字来保证多线程下的单例。
public class Singleton {
    private volatile Singleton instance = null;
    public Singleton getInstance() {
        if (instance == null) {
            synchronized(this) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}


推荐方法是Initialization on Demand Holder(IODH),详见http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

public class Singleton {
    static class SingletonHolder {
        static Singleton instance = new Singleton();
    }
    
    public static Singleton getInstance(){
        return SingletonHolder.instance;
    }
}
分享到:
评论
1 楼 kaneg 2008-11-27  
楼主的代码有问题:

public Singleton getInstance() {....}

要实现单例模式,这里应该要加static修饰符。

相关推荐

Global site tag (gtag.js) - Google Analytics