So I was using AtomicLong
and decided to have a look at its implementation, and noticed the following difference between 2 methods:
getAndAdd(long delta)
:
public final long getAndAdd(long delta) {
while (true) {
long current = get();
long next = current + delta;
if (compareAndSet(current, next))
return current;
}
}
incrementAndGet()
:
public final long incrementAndGet() {
for (;;) {
long current = get();
long next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
What struck me as odd is that both methods do almost exactly the same thing, but they were implemented using 2 different loops; a while
in the first and a for
in the second. As far as I can tell this would make no difference in performance. Is there a specific reason for this?