我有一个独特的情况。我希望能够使用compareAndSet()
的{{1}}功能,但有点麻烦。
通常在实际更改之前使用AtomicReference
与单个预期值进行比较。在我的情况下,要比较的预期值可能是许多值中的一个。
有没有办法使用compareAndSet()
执行此操作?如果没有,我应该使用哪些其他技术?也许只是传统上使用AtomicReference
?
答案 0 :(得分:2)
我假设您有'a
个预期值。在那种情况下......
Set
这对<T> boolean setIfInExpected(AtomicReference<T> ref, Set<?> expected, T newValue) {
while (true) {
T current = ref.get();
if (set.contains(current)) {
if (atomicReference.compareAndSet(current, newValue)) {
return true;
}
} else {
return false;
}
}
}
的使用方式来说很常见:它们会循环运行,直到compareAndSet
和AtomicReference
之间get
没有变化。