If another thread alternates, it will also successfully add it to the value.
Atomicity ensures that your increment happens, and if two threads try to increment, then two threads will succeed (and increase by two). This does not guarantee anything about any future value.
In your scenario, it looks like this:
public final long incrementAndGet() { for (;;) { long current = get(); long next = current + 1; if (compareAndSet(current, next)) { // Other thread. for (;;) { long current2 = get(); long next2 = current2 + 1; if (compareAndSet(current2, next2)) { return next2; } } return next; } } }
i.e. each thread gets its own incremental value.
Oldcurmudgeon
source share