AtomicInteger.incrementAndGet() vs. AtomicInteger.getAndIncrement()
When return value is not of interest, is there any (even irrelevant in practice) difference between AtomicInteger.getAndIncrement()
and AtomicInteger.incrementAndGet()
methods, when return value is ignored?
I'm thinking of differences like which would be more idiomatic, as well as which would put less load in CPU caches getting synchronized, or anything else really, anything to help decide which one to use more rationally than tossing a coin.
Solution 1:
Since no answer to the actual question has been given, here's my personal opinion based on the other answers (thanks, upvoted) and Java convention:
incrementAndGet()
is better, because method names should start with the verb describing the action, and intended action here is to increment only.
Starting with verb is the common Java convention, also described by official docs:
"Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized."
Solution 2:
The code is essentially the same so it does not matter:
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
Solution 3:
No, there's no difference (if you don't care about the return value).
The code of those methods (in the OpenJDK) differs only in that one uses return next
and the other uses return current
.
Both use compareAndSet
under the hood with the exact same algorithm. Both need to know both the old and the new value.