问题来源
以”懒汉式“单例模式为例(思想就是延迟高开销对象的初始化操做),代码以下。java
这是一个普通的POJO:安全
package myTest; import java.time.LocalDateTime; /** * <p>Title: DCLTestBean</p> * <p>Description: </p> * @author xiayuxuanmin * @date 2019年7月8日 */ public class DCLTestBean { private String username; private Integer password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getPassword() { return password; } public void setPassword(Integer password) { this.password = password; } public DCLTestBean() { System.out.println(Thread.currentThread().getName()+"~~~~~"+LocalDateTime.now()+" |DCLTestBean初始化了。"); } }
”懒汉式“单例:多线程
package myTest; /** * <p>Title: TestDCLDemo3</p> * <p>Description: </p> * @author xiayuxuanmin * @date 2019年7月8日 */ public class DCLDemo3 { private static DCLTestBean instance; public static DCLTestBean getInstance(){ if (instance==null){ //第一行 instance = new DCLTestBean(); //第二行 } return instance; } }
这个单例模式明显是线程不安全的,当多个线程调用时,他们可能都试图同时建立对象,或者可能最终得到对未彻底初始化对象的引用。能够简单测试一下:并发
package myTest; import java.util.concurrent.CountDownLatch; /** * <p>Title: TestDCLDemo3</p> * <p>Description: </p> * @author xiayuxuanmin * @date 2019年7月8日 */ public class TestDCLDemo3 { private static int count = 10; private static CountDownLatch countDownLatch = new CountDownLatch(count); private static DCLTestBean instance; public static DCLTestBean getInstance() { if(instance == null) { instance = new DCLTestBean(); } return instance; } public static void main(String[] args) { for(int i = 0;i < count;i++) { new Thread(()-> { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } getInstance(); },"thread-"+i).start(); countDownLatch.countDown(); } } }
执行结果:ide
thread-6~~~~~2019-07-08T09:45:34.604 |DCLTestBean初始化了。 thread-7~~~~~2019-07-08T09:45:34.605 |DCLTestBean初始化了。 thread-9~~~~~2019-07-08T09:45:34.604 |DCLTestBean初始化了。 thread-1~~~~~2019-07-08T09:45:34.606 |DCLTestBean初始化了。 thread-4~~~~~2019-07-08T09:45:34.605 |DCLTestBean初始化了。 thread-8~~~~~2019-07-08T09:45:34.606 |DCLTestBean初始化了。 thread-0~~~~~2019-07-08T09:45:34.605 |DCLTestBean初始化了。 thread-5~~~~~2019-07-08T09:45:34.605 |DCLTestBean初始化了。 thread-3~~~~~2019-07-08T09:45:34.605 |DCLTestBean初始化了。 thread-2~~~~~2019-07-08T09:45:34.605 |DCLTestBean初始化了。
DCLTestBean初始化实例屡次,这明显就违背了单例。性能
解决方法也很简单,直接加上synchronized便可:测试
package myTest; import java.util.concurrent.CountDownLatch; /** * <p>Title: TestDCLDemo3</p> * <p>Description: </p> * @author xiayuxuanmin * @date 2019年7月8日 */ public class TestDCLDemo3 { private static int count = 10; private static CountDownLatch countDownLatch = new CountDownLatch(count); private static DCLTestBean instance; public static synchronized DCLTestBean getInstance() { if(instance == null) { instance = new DCLTestBean(); } return instance; } public static void main(String[] args) { for(int i = 0;i < count;i++) { new Thread(()-> { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } getInstance(); },"thread-"+i).start(); countDownLatch.countDown(); } } }
执行结果:优化
thread-1~~~~~2019-07-08T09:50:21.112 |DCLTestBean初始化了。
可是在JDK1.6以前,synchronized属于重量级锁,若是getInstance()方法被多个线程频繁的调用,将会致使程序执行性能的降低。即只有在第一次调用getInstance()时将建立对象,而且在此期间只有少数尝试访问它的线程须要同步; 以后全部调用只得到对成员变量的引用。因为同步方法在某些极端状况下能够将性能下降100倍或更高,每次调用此方法时获取和释放锁的开销彷佛都是没必要要的:一旦初始化完成,获取并释放锁彷佛不必,因而下列方式优化这种状况:this
检查变量是否已初始化(未得到锁定)。若是已初始化,请当即返回。
得到锁定。
仔细检查变量是否已经初始化:若是另外一个线程首先得到了锁,它可能已经完成了初始化。若是是,则返回初始化变量。
不然,初始化并返回变量。
即双重检查锁,也就是DCL。spa
双重检查锁(DCL)
package myTest; /** * <p>Title: TestDCLDemo3</p> * <p>Description: </p> * @author xiayuxuanmin * @date 2019年7月8日 */ public class DCLDemo3 { private static DCLTestBean instance; public static DCLTestBean getInstance(){ if (instance==null){ //第一次检查 synchronized (DCLDemo3.class) {//同步锁 if(instance==null) { //第二次检查 instance = new DCLTestBean(); } } } return instance; } }
如上面代码所示,DCL本质上也就是减小了锁粒度,若是第一次检查instance不为null,那么就不须要执行下面的加锁和初始化操做。所以,能够大幅下降synchronized带来的性能开销。上面代码表面上看起来,彷佛一箭双鵰。多个线程试图在同一时间建立对象时,会经过加锁来保证只有一个线程能建立对象。在对象建立好以后,执行getInstance()方法将不须要获取锁,直接返回已建立好的对象。双重检查锁定看起来彷佛很完美,但这是一个错误的优化!当线程进行第一次检查的时候,代码读取到instance不为null时,instance引用的对象有可能尚未完成初始化。
DCL问题分析
在上面代码中:
instance = new DCLTestBean();
这段代码能够分为以下三行伪代码:
memory = allocate(); //1.分配对象内存空间 ctorInstance(memory); //2.在内存空间初始化对象 instance = memory; //3.设置instance指向刚分配的内存地址
上面3行伪代码中的2和3之间,可能会被重排序(在一些JIT编译器上,这种重排序是真实发生的)。
memory = allocate(); //1.分配对象内存空间 instance = memory; //3.设置instance指向刚分配的内存地址 ctorInstance(memory); //2.在内存空间初始化对象
以前介绍过(https://blog.csdn.net/Dongguabai/article/details/82290776),指令重排序能够保证串行语义一致,可是没有义务保证多线程间的语义也一致。也就是说上面3行伪代码的2和3之间虽然被重排序了,可是是不影响串行语义的。可是在多线程并发执行的状况就可能出现:
也就是说一个线程可能读到还没有初始化的DCLTestBean,而这个instance的确是!=null的。
能够用过一段代码来“模拟”下这种状况:
package myTest; import java.util.concurrent.TimeUnit; /** * <p>Title: DCLDemo</p> * <p>Description: </p> * @author xiayuxuanmin * @date 2019年7月8日 */ public class DCLDemo { private static volatile DCLTestBean instance; public static DCLTestBean getInstance() throws InterruptedException { System.out.println(Thread.currentThread().getName()+"-----等待执行同步方法"); if (instance == null) { synchronized (DCLDemo.class) { System.out.println(Thread.currentThread().getName()+"进入同步方法"); if (instance == null) { instance = new DCLTestBean(); System.out.println(Thread.currentThread().getName()+"new 了"); //当前线程睡眠3秒 //该数值要大于main方法中的sleep,保证thread3在启动的时候,已经执行过new方法的线程正在睡眠状态 TimeUnit.SECONDS.sleep(3); instance.setPassword(123); instance.setUsername("zhangsan"); } } } return instance; } public static void main(String[] args) throws InterruptedException { Runnable runnable = new Runnable() { @Override public void run() { try { DCLTestBean instance = DCLDemo.getInstance(); System.out.println(Thread.currentThread().getName()+"^^^^^"+instance.getUsername().toString()); } catch (InterruptedException e) { e.printStackTrace(); } } }; Thread thread1 = new Thread(runnable); Thread thread2 = new Thread(runnable); Thread thread3 = new Thread(runnable); thread1.start(); thread2.start(); //该代码的做用是让thread3延迟启动2秒(保证thread3在进入getInstance() 方法以后,在判断instance == null的时候,thread1 或者thread2已经执行过new()方法,而且执行new()方法的线程正处于睡眠状态) Thread.sleep(2000); thread3.start(); } }
运行结果为:
Thread-1-----等待执行同步方法 Thread-0-----等待执行同步方法 Thread-1进入同步方法 Thread-1~~~~~2019-07-08T10:00:40.881 |DCLTestBean初始化了。 Thread-1new 了 Thread-2-----等待执行同步方法 Exception in thread "Thread-2" java.lang.NullPointerException //出现空指针异常 at myTest.DCLDemo$1.run(DCLDemo.java:39) at java.lang.Thread.run(Thread.java:748) Thread-1^^^^^zhangsan Thread-0进入同步方法 Thread-0^^^^^zhangsan
在知晓了问题发生的根源以后,咱们能够想出两个办法来实现线程安全的延迟初始化。
1)不容许2和3重排序(在JDK 1.5后能够基于volatile来解决);
2)容许2和3重排序,但不容许其余线程“看到”这个重排序(可使用静态内部类解决);
基于volatile的解决方案
很简单,只须要添加volatile关键字便可:
package myTest; /** * <p>Title: TestDCLDemo3</p> * <p>Description: </p> * @author xiayuxuanmin * @date 2019年7月8日 */ public class DCLDemo3 { private static volatile DCLTestBean instance;//这里加上volatile public static DCLTestBean getInstance(){ if (instance==null){ //第一次检查 synchronized (DCLDemo3.class) {//同步锁 if(instance==null) { //第二次检查 instance = new DCLTestBean(); } } } return instance; } }
这个解决方案须要JDK 5或更高版本(由于从JDK 5开始使用新的JSR-133内存模型规范,这个规范加强了volatile的语义)。
当声明对象的引用为volatile后,下图中的3行伪代码中的2和3之间的重排序,在多线程环境中将会被禁止。当读一个volatile变量时,JMM会把该线程对应的本地内存置为无效。线程接下来将从主内存中读取变量。
时序图为: