AtomicInteger and Math.max

I was trying to get the maximum calcValue in a loop and I wanted it to be thread safe. So I decided to use AtomicInteger and Math.max, but I can't seem to find a solution, so 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 is that I am doing two operations, so it is not thread safe. How can I solve this? The only way to use synchronized

?

+3


source to share


1 answer


If Java 8 is available, you can use:

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

      



Which of the specification would be:

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

+4


source







All Articles