无锁同步-JAVA之Volatile、Atomic和CAS

一、概要

      本文是无锁同步系列文章的第二篇,主要探讨JAVA中的原子操做,以及如何进行无锁同步。html

      关于JAVA中的原子操做,咱们很容易想到的是Volatile变量、java.util.concurrent.atomic包和JVM提供的CAS操做。java

二、Volatile

    1)Volatile变量不具备原子性

           Volatile变量具备一种可见性,该特性能保证不一样线程甚至处理器核心在对这种类型的变量在读取的时候能读到最新的值。但Volatile变量不提供原子操做的保证。缓存

 

            下面咱们给出一个例子:数据结构

 1 public class test {  2   
 3   volatile static int someValue;  4   
 5   public static void main(String[] args) {  6     someValue = 1;  7     int b = someValue;  8  }  9 
10 }

      在这个例子中,咱们对一个int类型的volatile变量进行写和读,在这种场景下volatile变量的读和写操做是原子的(注意:这里指是读操做和写操做分别是原子的),而且jvm会为咱们保证happens-before语义(即会保证写操做在读操做以前发生,其实jvm给咱们提供的不单止是happens-before,具体详情咱们在本系列的下一篇博文再具体介绍)。咱们能够利用这个特性完成一小部分线程同步的需求。可是咱们须要注意下面这种状况。app

1 public class test { 2   
3   volatile static int someValue; 4   
5   public static void main(String[] args) { 6     someValue++; 7  } 8 
9 }

     在这里,咱们把读和写操做改为一个自增操做,那么这个自增操做是否是原子的呢?jvm

     答案是否认的。ide

     自增操做其本质是性能

1 int tmp = someValue; 2 tmp += 1; 3 someValue = tmp;

     这里包含读、加、写3个操做。对于int类型来讲,java保证这里面的读和写操做中是原子的,但不保证它们加在一块儿仍然是原子的。优化

     也正是因为这个特性,单独使用volatile变量还不足以实现计数器等包含计算的需求。可是若是使用恰当,这种变量将为线程间的同步带来无可比拟的性能提高。this

    2)Volatile变量如何保证可见性

      咱们知道现代的CPU为了优化性能,计算时通常不与内存直接交互。通常先把数据从内存读取到CPU内部缓存再进行操做。而不一样线程可能由不一样的CPU内核执行,极可能会致使某变量在不一样的处理器中保存着2个不一样副本的状况,致使数据不一致,产生意料以外的结果。那么java是怎么保证volatile变量在全部线程中的数据都是一致的呢?

      若对一个Volatile变量进行赋值,编译后除了生成赋值字节码外,还会生成一个lock指令。该指令是CPU提供的,能实现下面2个功能:

  1. 将CPU当前缓存行内的新数据写入内存
  2. 将其它CPU核内心包含本变量的缓存行无效化,以强制下次读取时到内存中读取

      上述过程基于CPU内部的一套缓存协议。具体能够查阅相关文档。

二、java.util.concurrent.atomic包和CAS

    对比volatile变量,atomic包给咱们提供了AtomicInteger、AtomicLong、AtomicBooleanAtomicReference、 AtomicIntegerArray、 AtomicLongArray、 AtomicReferenceArray等一系列类,提供了相应类型一系列的原子操做。它们的接口语义很是明显,下面咱们选AtomicInteger加以说明,读者能够触类旁通学会其余原子类的用法。

      AtomicInteger

          Get()/Set()

          下面咱们进入AtomicInteger类探秘,看看它是如何实现原子读写的。(下文使用的源码均来自JDK7)

 

 1     private volatile int value;  2 
 3     /**  4  * Gets the current value.  5  *  6  * @return the current value  7      */
 8     public final int get() {  9         return value; 10  } 11 
12     /** 13  * Sets to the given value. 14  * 15  * @param newValue the new value 16      */
17     public final void set(int newValue) { 18         value = newValue; 19     }

 

          没有错,就是利用咱们上面提到的volatile实现的。

      compareAndSet(int expect, int update)和weakCompareAndSet(int expect, int update)

          这就是著名的CAS(compare and set)接口。

          对比变量的值和expect是否相等,若是相等则将变量的值更新为update。参考第一篇,咱们能够根据这个特性实现一些无锁数据结构。事实上,JDK8中的java.util.concurrent包有很多数据结构被使用CAS优化,其中最著名的就是ConcurrentHashMap。

         而要说到weak版本的CAS接口有什么特别之处,它的注释说明它会"fail spuriously",可是其源码倒是如出一辙的。

 1     /**  2  * Atomically sets the value to the given updated value  3  * if the current value {@code ==} the expected value.  4  *  5  * @param expect the expected value  6  * @param update the new value  7  * @return true if successful. False return indicates that  8  * the actual value was not equal to the expected value.  9      */
10     public final boolean compareAndSet(int expect, int update) { 11         return unsafe.compareAndSwapInt(this, valueOffset, expect, update); 12  } 13 
14     /** 15  * Atomically sets the value to the given updated value 16  * if the current value {@code ==} the expected value. 17  * 18  * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> 19  * and does not provide ordering guarantees, so is only rarely an 20  * appropriate alternative to {@code compareAndSet}. 21  * 22  * @param expect the expected value 23  * @param update the new value 24  * @return true if successful. 25      */
26     public final boolean weakCompareAndSet(int expect, int update) { 27         return unsafe.compareAndSwapInt(this, valueOffset, expect, update); 28     }

          证实SUN JDK 7没有按照标准实现weak版本的接口,可是咱们没法保证之后的JDK是如何实现的。所以,不管什么时候,咱们都不该假定weak版本的CAS操做和非weak版本具备彻底一致的行为。

      其余经常使用接口

          int addAndGet(int delta)
          以原子方式将给定值与当前值相加。 功能等价于i=i+delta。

          int getAndAdd(int delta)
          以原子方式将给定值与当前值相加。 功能等价于{int tmp=i;i+=delta;return tmp;}。

          int getAndIncrement()
          以原子方式将当前值加 1。 功能等价于i++。

          int decrementAndGet()
          以原子方式将当前值减 1。 功能等价于--i。

          int getAndDecrement()
          以原子方式将当前值减 1。 功能等价于i--。

          int getAndSet(int newValue)
          以原子方式设置为给定值,并返回旧值。 功能等价于{int tmp=i;i=newValue;return tmp;}。

          int incrementAndGet()
          以原子方式将当前值加 1。 功能等价于++i。 

 三、CAS的ABA问题

  描述

    ABA问题的描述以下:

 

  1. 进程P1在共享变量中读到值为A
  2. P1被抢占,进程P2得到CPU时间片并执行
  3. P2把共享变量里的值从A改为了B,再改回到A
  4. P2被抢占,进程P1得到CPU时间片并执行
  5. P1回来看到共享变量里的值没有被改变,继续按共享变量没有被改变的逻辑执行

 

     显然,这极可能致使不可预料的错误。

  JAVA中的解决方案

     在java.util.concurrent.atomic包中,有一个AtomicStampedReference类,它提供了一个带有Stamp字段的CAS接口。

 1 /**  2  * Atomically sets the value of both the reference and stamp  3  * to the given update values if the  4  * current reference is {@code ==} to the expected reference  5  * and the current stamp is equal to the expected stamp.  6  *  7  * @param expectedReference the expected value of the reference  8  * @param newReference the new value for the reference  9  * @param expectedStamp the expected value of the stamp 10  * @param newStamp the new value for the stamp 11  * @return true if successful 12      */
13     public boolean compareAndSet(V expectedReference, 14  V newReference, 15                                  int expectedStamp, 16                                  int newStamp) { 17         Pair<V> current = pair; 18         return
19             expectedReference == current.reference &&
20             expectedStamp == current.stamp &&
21             ((newReference == current.reference &&
22               newStamp == current.stamp) ||
23  casPair(current, Pair.of(newReference, newStamp))); 24     }

    你们可能已经发现,这个Stamp参数就至关于一个版本号,当版本号和变量的值均一致的时候才容许更新变量。

    咱们试着用这个方法解决ABA问题:

  1. 进程P1在共享变量中读到值为A,Stamp为0。下面咱们用二元组(A, 0)表示共享变量的值
  2. P1被抢占,进程P2得到CPU时间片并执行
  3. P2把共享变量里的值从(A, 0)改为了(B, 1),再尝试把值修改成A,同时更新Stamp。即改成(A, 2)
  4. P2被抢占,进程P1得到CPU时间片并执行
  5. P1回来尝试更新共享变量的值,A在expectedStamp参数传入原数值0,却发现如今Stamp已经不是0了,CAS操做失败
  6. P1知道共享变量已经被改变,避免了BUG出现

    到这里,ABA问题被解决。

四、总结

    线程同步的方法不少,在适当的场景下灵活运用原子操做,避免使用锁能够提升咱们的程序性能。

相关文章
相关标签/搜索