简体   繁体   中英

Java AtomicInteger getAndIncrement() and compareAndSet

I am trying to understand how the current in getAndIncrement is updated, here is that piece of code.

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

I understand that compareAndSet will compare whether the current value is same as the value stored in register, if is it same then update the value in register with next.

The part I don't understand is that why doesn't it return next instead of current .

When enter the loop, current is set as an int and current is not a reference value, so if current is initialized as 5, then when it returns current, should it be 5 as well? Or when it returns current , the current will called get() again to get the updated value from register?

It's to improve concurrency.

If it returned next , the method would have to have synchronised code, otherwise another thread could modify the value between setting it and returning it.

By not returning next , only the actual modification needs synchronising, putting the responsibility, and optimization, of synchronization in one place; the compareAndSet() . When synchronization is shared between methods, it's much more complicated to coordinate safe state changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM