java中双检锁为什么要加上volatile关键字!

单线程版本:

class Foo { 
  private Helper helper = null;
  public Helper getHelper() {
    if (helper == null) 
        helper = new Helper();
    return helper;
    }
  // other functions and members...
  }

多线程版本(正确的):

class Foo { 
  private Helper helper = null;
  public synchronized Helper getHelper() {
    if (helper == null) 
        helper = new Helper();
    return helper;
    }
  // other functions and members...
  }

多线程版本(错误的):

class Foo { 
  private Helper helper = null;
  public Helper getHelper() {
    if (helper == null) 
      synchronized(this) {
        if (helper == null) 
          helper = new Helper();
      }    
    return helper;
    }
  // other functions and members...
  }

使用volatile关键字修改版:

class Foo {
    private volatile Helper helper = null;
    public Helper getHelper() {
        if (helper == null) {
            synchronized (this) {
                if (helper == null)
                    helper = new Helper();
            }
        }
        return helper;
    }
}

为什么不加volatile的双检锁是不起作用的?

The most obvious reason it doesn’t work it that the writes that initialize the Helper object and the write to the helper field can be done or perceived out of order. Thus, a thread which invokes getHelper() could see a non-null reference to a helper object, but see the default values for fields of the helper object, rather than the values set in the constructor.


If the compiler inlines the call to the constructor, then the writes that initialize the object and the write to the helper field can be freely reordered if the compiler can prove that the constructor cannot throw an exception or perform synchronization.

Even if the compiler does not reorder those writes, on a multiprocessor the processor or the memory system may reorder those writes, as perceived by a thread running on another processor.

在给helper对象初始化的过程中,jvm做了下面3件事:

1.给helper对象分配内存

2.调用构造函数

3.将helper对象指向分配的内存空间

由于jvm的”优化”,指令2和指令3的执行顺序是不一定的,当执行完指定3后,此时的helper对象就已经不在是null的了,但此时指令2不一定已经被执行。

假设线程1和线程2同时调用getHelper()方法,此时线程1执行完指令1和指令3,线程2抢到了执行权,此时helper对象是非空的。

所以线程2拿到了一个尚未初始化的helper对象,此时线程2调用这个helper就会抛出异常。

为什么volatile可以一定程度上保证双检锁ok?

1.volatile关键字可以保证jvm执行的一定的“有序性”,在指令1和指令2执行完之前,指定3一定不会被执行。
   为什么说是一定的”有序性”呢,因为对于非易失的读写,jvm仍然允许对volatile变量进行乱序读写


2.保证了volatile变量被修改后立刻刷新会驻内存中。



参考资料:
1.http://www.javaworld.com/article/2074979/java-concurrency/double-checked-locking–clever–but-broken.html
2.http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
3.http://www.importnew.com/18126.html


    原文作者:java锁
    原文地址: https://blog.csdn.net/Null_RuzZ/article/details/72530826
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞