How does “Compare And Set” in AtomicInteger works

非 Y 不嫁゛ 提交于 2019-12-03 05:01:07

问题


AtomicInteger works with two concepts : CAS and volatile variable.

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

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

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();

回答1:


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.

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.

Consider the following scenario:

  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.

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.

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.




回答2:


for (;;) is an infinite loop, so it will just retry the attempt.



来源:https://stackoverflow.com/questions/32634280/how-does-compare-and-set-in-atomicinteger-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!