首页 > 学院 > 开发设计 > 正文

Lazy Singleton的Java实现

2019-11-18 15:03:50
字体:
来源:转载
供稿:网友

由于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的时候初始化实例,并且保证了没有多线程并发问题。



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表