双检锁
java
class Solution {
private volatile Solution instance;
public Solution getInstance() {
Solution temp = instance;
if (temp == null) {
synchronized (this) {
if (temp == null) {
temp = instance = new Solution();
}
}
}
return temp;
}
}
为什么需要使用 volatile

如果不使用 volatile,会发生什么

为什么使用 synchronized

不使用 synchronized 会发生什么

为什么要使用双重检查

为什么需要先判断再加锁

synchronized 能保证可见性,为什么还需要 volatile

静态内部类
java
class Solution {
private static class Holder {
private static final Solution INSTANCE = new Solution();
}
public Solution getInstance() {
return Holder.INSTANCE;
}
}
