Java无锁同步_无锁同步-JAVA之Volatile、Atomic和CAS【转】

源地址:https://www.cnblogs.com/dengzz/p/5688021.html

1、概要

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

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

2、Volatile

1)Volatile变量不具有原子性

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

下面我们给出一个例子:

48304ba5e6f9fe08f3fa1abda7d326ab.png

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 }

48304ba5e6f9fe08f3fa1abda7d326ab.png

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

48304ba5e6f9fe08f3fa1abda7d326ab.png

1 public class test {

2

3 volatile static int someValue;

4

5 public static void main(String[] args) {

6 someValue++;

7 }

8

9 }

48304ba5e6f9fe08f3fa1abda7d326ab.png

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

答案是否定的。

自增操作其本质是

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个功能:

将CPU当前缓存行内的新数据写入内存

将其它CPU核心里包含本变量的缓存行无效化,以强制下次读取时到内存中读取

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

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

对比volatile变量,atomic包给我们提供了AtomicInteger、AtomicLong、AtomicBooleanAtomicReference、 AtomicIntegerArray、 AtomicLongArray、 AtomicReferenceArray等一系列类,提供了相应类型一系列的原子操作。它们的接口语义非常明显,下面我们选AtomicInteger加以说明,读者可以举一反三学会其他原子类的用法。

AtomicInteger

Get()/Set()

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

48304ba5e6f9fe08f3fa1abda7d326ab.png

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 }

48304ba5e6f9fe08f3fa1abda7d326ab.png

没有错,就是利用我们上面提到的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",但是其源码却是一模一样的。

48304ba5e6f9fe08f3fa1abda7d326ab.png

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 *

May fail spuriously

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 }

48304ba5e6f9fe08f3fa1abda7d326ab.png

证明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问题的描述如下:

进程P1在共享变量中读到值为A

P1被抢占,进程P2获得CPU时间片并执行

P2把共享变量里的值从A改成了B,再改回到A

P2被抢占,进程P1获得CPU时间片并执行

P1回来看到共享变量里的值没有被改变,继续按共享变量没有被改变的逻辑执行

显然,这很可能导致不可预料的错误。

JAVA中的解决方案

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

48304ba5e6f9fe08f3fa1abda7d326ab.png

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 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 }

48304ba5e6f9fe08f3fa1abda7d326ab.png

大家可能已经发现,这个Stamp参数就相当于一个版本号,当版本号和变量的值均一致的时候才允许更新变量。

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

进程P1在共享变量中读到值为A,Stamp为0。下面我们用二元组(A, 0)表示共享变量的值

P1被抢占,进程P2获得CPU时间片并执行

P2把共享变量里的值从(A, 0)改成了(B, 1),再尝试把值修改为A,同时更新Stamp。即改为(A, 2)

P2被抢占,进程P1获得CPU时间片并执行

P1回来尝试更新共享变量的值,A在expectedStamp参数传入原数值0,却发现现在Stamp已经不是0了,CAS操作失败

P1知道共享变量已经被改变,避免了BUG出现

到这里,ABA问题被解决。

4、总结

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值