使用AtomicReference对多个预期值进行比较和设置

时间:2015-06-10 21:48:30

标签: java multithreading concurrency atomic atomicity

我有一个独特的情况。我希望能够使用compareAndSet()的{​​{1}}功能,但有点麻烦。

通常在实际更改之前使用AtomicReference与单个预期值进行比较。在我的情况下,要比较的预期值可能是许多值中的一个。

有没有办法使用compareAndSet()执行此操作?如果没有,我应该使用哪些其他技术?也许只是传统上使用AtomicReference

1 个答案:

答案 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; } } } 的使用方式来说很常见:它们会循环运行,直到compareAndSetAtomicReference之间get没有变化。