AtomicInteger.updateAndGet() 和 AtomicInteger.accumulateAndGet() 之间有什么功能差异吗?

2022-09-04 03:18:40

是否有任何情况不能替换为 ,或者它只是对方法引用的方便?AtomicInteger.accumulateAndGet()AtomicInteger.updateAndGet()

这是一个简单的例子,我没有看到任何功能差异:

AtomicInteger i = new AtomicInteger();
i.accumulateAndGet(5, Math::max);
i.updateAndGet(x -> Math.max(x, 5));

显然,和 也是如此。getAndUpdate()getAndAccumulate()


答案 1

如有疑问,您可以研究实现

public final int accumulateAndGet(int x,
                                  IntBinaryOperator accumulatorFunction) {
    int prev, next;
    do {
        prev = get();
        next = accumulatorFunction.applyAsInt(prev, x);
    } while (!compareAndSet(prev, next));
    return next;
}

public final int updateAndGet(IntUnaryOperator updateFunction) {
    int prev, next;
    do {
        prev = get();
        next = updateFunction.applyAsInt(prev);
    } while (!compareAndSet(prev, next));
    return next;
}

它们仅在单行中有所不同,显然可以通过以下方式轻松表示:accumulateAndGetupdateAndGet

public final int accumulateAndGet(int x,
                                  IntBinaryOperator accumulatorFunction) {
    return updateAndGet(prev -> accumulatorFunction.applyAsInt(prev, x));
}

因此,这是一些更基本的操作,是一个有用的快捷方式。如果您没有有效地最终确定,这样的快捷方式可能特别有用:updateAndGetaccumulateAndGetx

int nextValue = 5;
if(something) nextValue = 6;
i.accumulateAndGet(nextValue, Math::max);
// i.updateAndGet(prev -> Math.max(prev, nextValue)); -- will not work

答案 2

在某些情况下,可以使用 来避免创建实例。accumulateAndGet

这并不是真正的功能差异,但了解它可能很有用。

请考虑以下示例:

void increment(int incValue, AtomicInteger i) {
    // The lambda is closed over incValue. Because of this the created
    // IntUnaryOperator will have a field which contains incValue. 
    // Because of this a new instance must be allocated on every call
    // to the increment method.
    i.updateAndGet(value -> incValue + value);

    // The lambda is not closed over anything. The same
    // IntBinaryOperator instance can be used on every call to the 
    // increment method.
    //
    // It can be cached in a field, or maybe the optimizer is able 
    // to reuse it automatically.
    IntBinaryOperator accumulatorFunction =
            (incValueParam, value) -> incValueParam + value;

    i.accumulateAndGet(incValue, accumulatorFunction);
}

实例创建通常成本不高,但在性能敏感位置经常使用的短操作中,删除实例非常重要。

有关何时重用 lambda 实例的更多信息,请参阅此答案


推荐