Java单例模式的双重检查锁定实现
在各类设计模式中,单例模式因其应用广泛且逻辑相对简单而备受青睐。为确保系统中仅存在唯一的一个对象实例,常规做法是结合同步锁与双重检查机制进行构建,具体代码实现如下所示。
public class SingletonTest {
private SingletonTest(){
}
private static SingletonTest instance;
public static SingletonTest getInstance(){
if(instance == null){
synchronized (SingletonTest.class){
if(instance == null){
instance = new SingletonTest();
}
}
}
return instance;
}
}
这种写法的要点主要有如下几个,1,私有构造函数,即不允许直接调用构造函数new一个对象。2,静态实例。3,静态获取示例的方法。首先判断instance是否为null,然后加锁,然后再判断instance是否为null,之后进行初始化。最后返回示例。
然而,仅仅做到上述步骤是否就万无一失了呢?答案是否定的。
鉴于JVM内存模型的架构特性,每个线程拥有独立的工作内存,它是主内存中数据的副本,两者之间并非保持实时同步。当某个线程完成了单例对象的创建并写入主内存时,其他线程可能无法立即感知这一变化。因此,前文代码中的instance变量必须添加volatile修饰符,以禁止指令重排序并保证可见性,从而真正实现严格的单例语义。修正后的代码如下。
public class SingletonTest {
private SingletonTest(){
}
private static volatile SingletonTest instance;
public static SingletonTest getInstance(){
if(instance == null){
synchronized (SingletonTest.class){
if(instance == null){
instance = new SingletonTest();
}
}
}
return instance;
}
}
总结
以上内容涵盖了本文的全部知识点,期望能为各位的学习或工作提供有价值的参考,感谢大家的支持。若需探索更多相关技术细节,请参阅下方的推荐链接。