现在的位置: 首页 > 综合 > 正文

Lazy Singleton的Java实现

2013年10月11日 ⁄ 综合 ⁄ 共 658字 ⁄ 字号 评论关闭

由于Java的内存模型的原因,在C++中的双重检查模型在Java中不可用:

public static Singleton getInstance() {
    if(instance==null) {
        synchronized(this) {
            if(instance==null) {
                instance=new Singleton();
            }
        }
    }
    return instance;
}

如果采用synchronized方法,又会严重影响性能:

public static synchronized Singleton getInstance() {
    if(instance==null) {
        instance=new Singleton();
    }
    return instance;
}

如何实现Lazy Singleton?方法是利用Java的ClassLoader即时装载特性,使用一个SingletonHolder实现:

static class SingletonHolder {
    static Singleton instance = new Singleton();
}

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

这里利用Java ClassLoader特性,在第一次加载SingletonHolder的时候初始化实例,并且保证了没有多线程并发问题。

抱歉!评论已关闭.