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