Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AtomicInteger and Math.max

I was trying to get the maximum value of a calculatedValue in a cycle and I wanted it to be thread safe. So I decided to use AtomicInteger and Math.max, but I can't find a solution so that the operation can be considered atomic.

AtomicInteger value = new AtomicInteger(0);


// Having some cycle here... {
    Integer anotherCalculatedValue = ...;
    value.set(Math.max(value.get(), anotherCalculatedValue));
}

return value.get()

The problem with that is that I make two operations, therefore is not threadsafe. How can I solve this? The only way is to use synchronized?

like image 314
Pablo Matias Gomez Avatar asked Mar 31 '17 18:03

Pablo Matias Gomez


1 Answers

If Java 8 is available you can use:

AtomicInteger value = new AtomicInteger(0);
Integer anotherCalculatedValue = ...;
value.getAndAccumulate(anotherCalculatedValue, Math::max);

Which from the specification will:

Atomically updates the current value with the results of applying the given function to the current and given values, returning the previous value.

like image 55
William DeRaad Avatar answered Oct 17 '22 22:10

William DeRaad