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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With