简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM