如何根据条件更新原子?

How to update an Atomic based on a condition?

如果 AtomicInteger 的当前值小于给定值,如何更新它?思路是:

AtomicInteger ai = new AtomicInteger(0);
...
ai.update(threadInt); // this call happens concurrently
...
// inside AtomicInteger atomic operation
synchronized {
    if (ai.currentvalue < threadInt)
        ai.currentvalue = threadInt;
}

如果您使用的是 Java 8,则可以使用 AtomicInteger 中的一种新更新方法,您可以传递一个 lambda 表达式。例如:

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);

如果你没有 Java 8,你可以像这样使用 CAS 循环 :

while (true) {
    int currentValue = ai.get();
    if (newValue > currentValue) {
        if (ai.compareAndSet(currentValue, newValue)) {
            break;
        }
    }
}

如果我没有 Java 8,我可能会创建一个实用方法,例如:

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;
}

从 OP 的代码中,它会被这样调用:

AtomicInteger ai = new AtomicInteger(0);

int threadInt = ...

// Update ai atomically, but only if the current value is less than threadInt
setIfIncreases(ai, threadInt);