代码
public class SamlUtil
{
private static SamlUtil samlUtil;
private static final Object lock = new Object();
private SamlUtil() {
}
public static SamlUtil getInstance() {
SamlUtil temp = samlUtil;
if (temp == null) {
synchronized (lock) {
temp = samlUtil;
if (temp == null) {
temp = new SamlUtil();
samlUtil = temp;
}
}
}
return samlUtil;
}
}
要点
为什么要double check?
防止多线程竞争状态下单例不“单”
为什么创造temp?
避免指令重排造成单例无实例
可以不引入temp变量,使用volatile关键字
volatile的主要作用是保证变量在多线程上的可见性,它不会改变单线程程序的执行顺序。
public class SamlUtil
{
private static volatile SamlUtil samlUtil;
private static final Object lock = new Object();
private SamlUtil() {
}
public static SamlUtil getInstance() {
if (samlUtil == null) {
synchronized (lock) {
if (samlUtil == null) {
samlUtil = new SamlUtil();
}
}
}
return samlUtil;
}
}
Ref
https://juejin.cn/post/7049327348784562213
标签:Java,temp,lock,模式,static,private,单例,SamlUtil,samlUtil From: https://www.cnblogs.com/talentzemin/p/17896222.html