Home > database >  How to manage the concurrent access in AtomicLong class?
How to manage the concurrent access in AtomicLong class?

Time:10-01

Studying the atomic classes i found this code :

public class AtomicCounter {

private AtomicLong count = new AtomicLong(0);

public void increment() {
    boolean updated = false;
    while(!updated){
        long prevCount = count.get();
        updated = count.compareAndSet(prevCount, prevCount   1);
    }
}

public long count() {
    return count.get();
}

And i asked myself what if the following scenario occurs :

  1. In thread A the boolean updated is changed to true after calling the method compareAndSet.

  2. In thread B the instruction boolean updated = false; is executed and the boolean updated is changed again to be false

  3. In thread A the loop while check the value of the boolean updated which recently changed to false so another leap will be take a place.

In this case the thread A will take a new leap in while even it has already change the value of updated to true because in the time between of this change and the checking of updated by while the other thread B has changed the value of updated to false. How far this scenario is true ?

CodePudding user response:

Local variable not shared between threads

You misunderstand how local variables work with threads.

  • Related