zoukankan      html  css  js  c++  java
  • 无锁同步-JAVA之Volatile、Atomic和CAS

    1、概要

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

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

    2、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,具体详情我们在本系列的下一篇博文再具体介绍)。我们可以利用这个特性完成一小部分线程同步的需求。但是我们需要注意下面这种情况。

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

         在这里,我们把读和写操作改成一个自增操作,那么这个自增操作是不是原子的呢?

         答案是否定的。

         自增操作其本质是

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

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

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

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

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

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

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

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

    2、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。 

     3、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问题被解决。

    4、总结

        线程同步的方法很多,在适当的场景下灵活运用原子操作,避免使用锁可以提高我们的程序性能。

  • 相关阅读:
    byte在计算机中的存储方式--Double.byteValue()的输出结果思考
    启动Eclipse时An internal error occurred during: "Initializing Java Tooling".错误
    java实现两个int数交换
    cmd编译运行java
    java配置环境变量
    使用jQuery获取session中存储的list集合
    搭建ssm框架,可实现登录和数据展示以及增删改查
    java 生成UUID
    jQuery serialize()方法获取不到数据,alert结果为空
    SpringMVC架构的项目,js,css等静态文件导入有问题
  • 原文地址:https://www.cnblogs.com/dengzz/p/5688021.html
Copyright © 2011-2022 走看看