如何“比较和设置”在AtomicInteger工作 [英] How does "Compare And Set" in AtomicInteger works

查看:358
本文介绍了如何“比较和设置”在AtomicInteger工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AtomicInteger 使用两个概念:CAS和 volatile 变量。

AtomicInteger works with two concepts : CAS and volatile variable.

使用 volatile 变量确保当前值对所有线程都可见,并且不会被缓存。

Using volatile variable insures that the current value will be visible to all threads and it will not be cached.

但我对CAS(比较和设置)概念感到困惑,如下所述:

But I am confused over CAS(compare AND set) concept which is explained below:

public final int getAndIncrement() {
    for (;;) {
        int current = get();
        int next = current + 1;
        if (compareAndSet(current, next))
            return current;
    }
 }

我的问题是 if(compareAndSet(current,next)返回 false ?值是否会更新?
在这种情况下,当a时会发生什么线程正在执行以下情况:

My question is that whatif(compareAndSet(current, next) returns false? Will the value not be updated? In this case what will happen when a Thread is executing the below case:

private AtomicInteger count = new AtomicInteger();
count.incrementAndGet();


推荐答案

原子对象使用比较和交换机制使它们成为原子 - 即可以保证值 >指定,现在为新值。

The atomic objects make use of Compare and Swap mechanism to make them atomic - i.e. it is possible to guarantee that the value was as specified and is now at the new value.

您发布的代码会不断尝试将当前值设置为1比以前更多。记住另一个线程也可以执行 get 并尝试设置它。如果两个线程相互竞争以更改它的值其中一个增量可能会失败。

The code you posted continually tries to set the current value to one more than it was before. Remember that another thread could also have performed a get and is trying to set it too. If two threads race each other to change the value it is possible for one of the increments to fail.

请考虑以下情形:


  1. 线程1调用获取并获取值 1

  2. 线程1计算 next 2

  3. 线程2调用获取并获取值 1

  4. 线程2计算 next 2

  5. 两个线程都尝试写入值。

  1. Thread 1 calls get and gets the value 1.
  2. Thread 1 calculates next to be 2.
  3. Thread 2 calls get and gets the value 1.
  4. Thread 2 calculates next to be 2.
  5. Both threads try to write the value.

现在因为原子 - 只有一个线程会成功,另一个会收到 false 来自 compareAndSet 并再次四处走动。

Now because of atomics - only one thread will succeed, the other will recieve false from the compareAndSet and go around again.

如果不使用这种机制,那很可能两个线程都增加了值,导致实际上只有一个增量。

If this mechanism was not used it would be quite possible for both threads to increment the value resulting in only one increment actually being done.

(;;) $ c>只有在许多线程同时写入变量时才会真正循环。在非常重的负载下,它可能会循环几次,但它应该很快完成。

The confusing infinite loop for(;;) will only really loop if many threads are writing to the variable at the same time. Under very heavy load it may loop around several times but it should complete quite quickly.

这篇关于如何“比较和设置”在AtomicInteger工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆