How does "Compare And Set" work in AtomicInteger

AtomicInteger works with two concepts: CAS and volatile .

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

But I am confused by the concept of CAS (compare and install), 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 if(compareAndSet(current, next) returns false ? Will the value not change? In this case, what happens when Thread executes the following case:

 private AtomicInteger count = new AtomicInteger(); count.incrementAndGet(); 
+7
java multithreading concurrency volatile
source share
2 answers

Atomic objects use the Compare and Swap mechanism to make them atomic - that is, you can guarantee that the value was , as indicated, and now with the new value.

The code you posted is constantly trying to set the current value to another than before. Remember, another thread could also get and try to install it. If two threads diverge from each other to change the value, it is possible that one of the increments will fail.

Consider the following scenario:

  • Topic 1 calls get and gets the value 1 .
  • In thread 1, next calculated as 2 .
  • Thread 2 calls get and gets the value 1 .
  • In thread 2, next calculated as 2 .
  • Both threads try to write the value.

Now, due to atomic science - only one thread will succeed , the other will get false from compareAndSet and go down again.

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

The confusing infinite loop for(;;) will really loop only if many threads write to the variable at the same time. With a very large load, it can rotate several times, but it should end rather quickly.

+10
source share

for (;;) is an infinite loop, so it will just try again.

+5
source share

All Articles