简体   繁体   English

AtomicInteger和Math.max

[英]AtomicInteger and Math.max

I was trying to get the maximum value of a calculatedValue in a cycle and I wanted it to be thread safe. 我试图在一个循环中获得calculateValue的最大值,我希望它是线程安全的。 So I decided to use AtomicInteger and Math.max, but I can't find a solution so that the operation can be considered atomic. 所以我决定使用AtomicInteger和Math.max,但我找不到解决方案,因此可以将操作视为原子操作。

AtomicInteger value = new AtomicInteger(0);


// Having some cycle here... {
    Integer anotherCalculatedValue = ...;
    value.set(Math.max(value.get(), anotherCalculatedValue));
}

return value.get()

The problem with that is that I make two operations, therefore is not threadsafe. 问题是我做了两个操作,因此不是线程安全的。 How can I solve this? 我怎么解决这个问题? The only way is to use synchronized ? 唯一的方法是使用synchronized

If Java 8 is available you can use: 如果Java 8可用,您可以使用:

AtomicInteger value = new AtomicInteger(0);
Integer anotherCalculatedValue = ...;
value.getAndAccumulate(anotherCalculatedValue, Math::max);

Which from the specification will: 规范中将:

Atomically updates the current value with the results of applying the given function to the current and given values, returning the previous value. 原子地使用将给定函数应用于当前值和给定值的结果更新当前值,返回先前的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM