11

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;
}
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
Stephan Rozinsky
  • 553
  • 2
  • 6
  • 21
  • pls paste working code i.e. without any compilation error.. – SMA Apr 14 '15 at 11:50
  • Your posted code snippet make no sense. You first update `ai` (whatever you mean with .update()) and after you check the value with the new one. – SubOptimal Apr 14 '15 at 11:55
  • 3
    This is a good question and it makes perfect sense. For the criticism: It is impossible for the OP to write working code for this. If he did, he would need to know the answer, so he can only post pseudo-code. – Daniel S. Apr 14 '15 at 12:00

3 Answers3

23

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);
Jesper
  • 202,709
  • 46
  • 318
  • 350
5

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);
Mikko Östlund
  • 2,635
  • 3
  • 17
  • 14
3

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;
        }
    }
}
Olivier Croisier
  • 6,139
  • 25
  • 34