为什么单例模式中的懒汉模式要用双重校验锁
首先懒汉模式的用双重校验锁的代码如下:
public class ST {
private static volatile ST st = null;
private ST() {
}
public static ST getInstance() {
if (st == null) {
synchronized (ST.class) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(st == null){
st = new ST();
}
}
}
return st;
}
}
为了看出问题,这里在进入第一重锁之后让线程sleep。
第一次判断是否为null 可以提高程序的效率,如果不为null 就不执行代码块中的程序,直接返回非空对象。第二次判断是否为null 则是为了实现线程安全的单例模式,如果没有第二次判断,线程A通过了第一次判断还没有new对象的时候时间片刚好用完,这时候线程B也通过了第一次判断,此时线程B new了一个对象,B执行完之后线程A醒过来继续执行new 对象。会发现,这时候就new了两个对象,不能保证单例。
为了测试,只用外层的null判断的代码如下:
public class ST {
private static volatile ST st = null;
private ST() {
}
public static ST getInstance() {
if (st == null) {
synchronized (ST.class) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
st = new ST();
}
}
return st;
}
}
测试代码
public class Demo1 {
public static void main(String[] args) {
new Thread(() -> {
ST instance = ST.getInstance();
System.out.println(instance);
}).start();
new Thread(() -> {
ST instance = ST.getInstance();
System.out.println(instance);
}).start();
new Thread(() -> {
ST instance = ST.getInstance();
System.out.println(instance);
}).start();
new Thread(() -> {
ST instance = ST.getInstance();
System.out.println(instance);
}).start();
}
}
输出结果
root.ST@5bdc5f4f
root.ST@8fe093e
root.ST@314f5249
root.ST@5ba77774
发现此时四个线程生成了四个不同的对象。所以懒汉式的单例一定要使用双重校验锁