单例模式的双重检查生成
时间: 2023-03-23 15:02:36 浏览: 75
在单例模式中,我们希望某个类在整个应用程序中只存在一个实例,因此需要进行双重检查来确保只有一个实例被创建。以下是一个用于在Java中实现单例模式的双重检查示例:
```java
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
```
在上面的代码中,`volatile`关键字确保在多线程环境下正确地处理`uniqueInstance`变量。在getInstance()方法中,首先检查`uniqueInstance`是否为null,如果为null,则通过`synchronized`关键字同步代码块来避免多个线程同时进入该方法并创建多个实例。在同步块内部再次检查`uniqueInstance`是否为null,以确保在等待获取锁的过程中没有其他线程创建了实例。
这种实现方式既线程安全又高效。如果没有双重检查,每次调用`getInstance()`方法都将同步整个方法,这将导致性能下降。