Simply, share long
between threads
safetly just neet volatile
keyword like:
private volatile long value;
So, if you just use it like this, it will enought.
But for your question, if you examine source codes
AtomicLong source:
public final void set(long newValue) {
value = newValue;
}
LongAccumulator source:
public void accumulate(long x) {
Cell[] as; long b, v, r; int m; Cell a;
if ((as = cells) != null ||
(r = function.applyAsLong(b = base, x)) != b && !casBase(b, r)) {
boolean uncontended = true;
if (as == null || (m = as.length - 1) < 0 ||
(a = as[getProbe() & m]) == null ||
!(uncontended =
(r = function.applyAsLong(v = a.value, x)) == v ||
a.cas(v, r)))
longAccumulate(x, function, uncontended);
}
}
final void longAccumulate(long x, LongBinaryOperator fn,
boolean wasUncontended) {
//.... a lot of codes
}
So, AtomicLong
is better for performance because of less code :)