How to update an AtomicInteger
if its current value is less than the given value? The idea is:
AtomicInteger ai = new AtomicInteger(0);
...
ai.update(threadInt); // this call happens concurrently
...
// inside AtomicInteger atomic operation
synchronized {
if (ai.currentvalue < threadInt)
ai.currentvalue = threadInt;
}
If you are using Java 8 you can use one of the new update methods in AtomicInteger
, which you can pass a lambda expression. For example:
AtomicInteger ai = new AtomicInteger(0);
int threadInt = ...
// Update ai atomically, but only if the current value is less than threadInt
ai.updateAndGet(value -> value < threadInt ? threadInt : value);
If you don't have Java 8, you can use a CAS-loop like this :
while (true) {
int currentValue = ai.get();
if (newValue > currentValue) {
if (ai.compareAndSet(currentValue, newValue)) {
break;
}
}
}
If I didn't have Java 8, I would probably create a utility method, something like:
public static boolean setIfIncreases(AtomicInteger ai, int newValue) {
int currentValue;
do {
currentValue = ai.get();
if (currentValue >= newValue) {
return false;
}
} while (!ai.compareAndSet(currentValue, newValue));
return true;
}
From the OP's code, it would then be invoked thus:
AtomicInteger ai = new AtomicInteger(0);
int threadInt = ...
// Update ai atomically, but only if the current value is less than threadInt
setIfIncreases(ai, threadInt);
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