警告:问题有点长,但分离线下方的部分仅用于好奇.
Oracle的AtomicInteger的JDK 7实现包括以下方法:
public final int addAndGet(int delta) {
for (;;) {
int current = get();
int next = current + delta; // Only difference
if (compareAndSet(current, next))
return next;
}
}
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1; // Only difference
if (compareAndSet(current, next))
return next;
}
}
Run Code Online (Sandbox Code Playgroud)
很明显第二种方法可以写成:
public final int incrementAndGet() {
return addAndGet(1);
}
Run Code Online (Sandbox Code Playgroud)
在该类中还有其他几个类似代码重复的例子.我想不出有任何理由这样做,而是考虑性能(*).我很确定作者在确定设计之前做了一些深入的测试.
为什么(或在什么情况下)第一个代码比第二个代码表现更好?
(*)我无法抗拒,但写了一个快速的微基准.它显示(后JIT)系统性差距为2-4%,有利于addAndGet(1)vs incrementAndGet()(虽然很小,但它非常一致).说实话,我无法真正解释这个结果......
输出:
incrementAndGet():905 …