如何根据条件更新Atomic?

时间:2015-04-14 11:49:45

标签: java concurrentmodification atomicinteger

如果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; } ?这个想法是:

{{1}}

3 个答案:

答案 0 :(得分:17)

如果您使用的是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);

答案 1 :(得分:3)

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

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

答案 2 :(得分:1)

如果我没有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);