I need to perform the following operation:
// average, total, elapsed are Long's
average = ( ( total * average ) + elapsed ) / (++total);
But I want to use AtomicLong
This is what I'm trying but I don't quite get if it is correct:
average.set( (( total.get() * average.get() ) + elapsed) / total.getAndIncrement() );
How can I tell if this is correct?
The assumption is that these calculations are going to be called by multiple threads concurrently. I initially did not take that into effect.
If you want to use the
AtomicLongto do the pre-increment calculation, then you should do something like:This still has race conditions however since the average could be updated by someone else between the
average.get()and theaverage.set()call which would not be taken into effect in the update.To be completely sure, you need to (as @user1657364 mentioned in their answer) lock around a guard object.