AtomicLong.set vs LongAccumulator.accumulate performance java?

251 views Asked by At

I have a use case for high concurrent writes to an AtomicLong variable. I just need to set current epoc time in this variable. What would be the fastest way to do so?

Is LongAccumulator.accumulate a better alternative to AtomicLong.set, are there any stats out there which tell after how many concurrent requests/second which is better if I just want to set variable to some value without any addition or calculation?

2

There are 2 answers

0
utrucceh On

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 :)

0
pveentjer On

Primitive volatile and atomic long will perform the same for a simple set because atomic long uses volatile long field internally. Doing few million concurrent updates per second on the same volatile will for typical apps not be a performance problem.

Also I would be careful optimizing code if you don't know if something is a performance problem at all.