在阿里巴巴编码规范中,在高并发情况下,LongAdder的效率比AtomicLong要高,因为减少了AtomicLong空自旋的效率损耗,通过采用热点分离的思想来减少并发更新的竞争。
但是它也有一个问题,就是在计数时,如果有并发的更新,可能导致结果不正确。
/**
* Returns the current sum. The returned value is <em>NOT</em> an
* atomic snapshot; invocation in the absence of concurrent
* updates returns an accurate result, but concurrent updates that
* occur while the sum is being calculated might not be
* incorporated.
*
* @return the sum
*/
public long sum() {
Cell[] as = cells; Cell a;
long sum = base;
if (as != null) {
for (int i = 0; i < as.length; ++i) {
if ((a = as[i]) != null)
sum += a.value;
}
}
return sum;
}