参考文档
https://www.cnblogs.com/dolphin0520/p/3920373.html
单列设计:懒汉模式
- 饿汉式
public void Lazy{
private void lazy(){}
private static Lazy lazy = new Lazy();
public static Lazy getInstence(){
return Lazy;
}
}
- 经典懒汉设计
public void Lazy{
private void lazy(){}
private static Lazy lazy;
public static Lazy getInstence(){
if(lazy == null){
lazy = new lazy();
}
return Lazy;
}
}
- 线程安全懒汉式
public void Lazy{
private volatile static Lazy lazy;
private volatile static String my = false;
private static void lazy(){
if(my){
throw Exception;
}
}
public static LazygetInstence(){
if(lazy == null){
synchronized(Lazy.class){
if(lazy == null){
lazy = new lazy();
}
}
}
return Lazy;
}
}
其中存在不足,多线程时,无法保证只创建一个单列,由此引申加锁和volatile限制,来保证可见性和禁止进行指令重排序
- volatile无法保证对变量的任何操作都是原子性的。
- volatile能保证有序性
- volatile保证了不同线程对这个变量进行操作时的可见性
使用场景:
使用volatile必须具备以下2个条件:
1)对变量的写操作不依赖于当前值
2)该变量没有包含在具有其他变量的不变式中