I have a Counter class that stores value as AtomicInteger.
(我有一个Counter类,将值存储为AtomicInteger。)
That class should be thread safe. (该类应该是线程安全的。)
I have method boolean consume(int number)
that should decrement counter and return true
if counter >= number
, and should not change counter and return false
if counter < number
(我boolean consume(int number)
,该方法应减少counter并在counter >= number
返回true
,并且不应更改counter并在counter < number
返回false
)
class Counter {
AtomicInteger counter = new AtomicInteger(initialValue);
boolean consume(int number) {
counter.accumulateAndGet(number, (prev, next) -> {
if (number <= prev) {
return prev - number;
} else {
// not modify the previous number;
return prev;
}
});
return ???
}
}
And I don't know if the function applied or not.
(而且我不知道该功能是否适用。)
I found the following solution (我发现以下解决方案)
boolean consume(int number) {
AtomicBoolean result = new AtomicBoolean(false);
counter.accumulateAndGet(number, (prev, next) -> {
if (number <= prev) {
result.set(true);
return prev - number;
// function applied
} else {
result.set(false);
// not modify the previous number;
return prev;
}
});
return result.get();
}
but javadoc of accumulateAndGet
sais:
(但是accumulateAndGet
javadoc说:)
The function should be side-effect-free, since it may be re-applied when attempted updates fail due to contention among threads.
(该函数应无副作用,因为当尝试更新由于线程间的争用而失败时,可以重新应用该函数。)
So, my solution has side effects.
(因此,我的解决方案有副作用。)
Is it safe to use? (使用安全吗?)
If not, how can I get the same result? (如果没有,我如何获得相同的结果?)
ask by a3dsfcv translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…