AtomicReference compareAndSet:字符串引用与值相等
AtomicReference compareAndSet: String reference vs value equality
假设您有:
AtomicReference<String> ref = new AtomicReference<>("");
bool ok1 = ref.compareAndSet(x1, x2); // x1 has value "", x2 has value "test"
bool ok2 = ref.compareAndSet(x3, x4); // x2 has value "test", x4 has value "updated"
在以下情况下,"ok2" 的值是多少(因此,"ref" 的值是多少)。
- x2 和 x3 是同一个引用,即 x2 == x3
- 它们不是,即 x2 != x3(但是 x2.equals(x3))
我的理解是,在场景2中,更新会失败,即ok2为false。
如果我的理解是正确的,那么以价值平等重现这种行为的最佳方式是什么?换句话说,您将如何设置一个适用于字符串相等性的原子 compareAndSet 操作(即在两种情况下有效 ok==true)?
谢谢
您可以通过循环执行此操作,方法是提取值、比较然后更新,除非值在提取和尝试更新之间发生变化:
static <T> boolean setIfEqualTo(AtomicReference<T> ref, T old, T value) {
T current;
do {
current = ref.get();
if (!Objects.equals(current, old)) {
// They're not equal, so give up on trying to update.
return false;
}
} while (
// Try to update, if the value is still equal to `current`.
!ref.compareAndSet(current, value));
return true;
}
除非竞争激烈,否则不会循环,或者可能会循环一次(如果你不走运)或两次(如果你真的很不走运)。
假设您有:
AtomicReference<String> ref = new AtomicReference<>("");
bool ok1 = ref.compareAndSet(x1, x2); // x1 has value "", x2 has value "test"
bool ok2 = ref.compareAndSet(x3, x4); // x2 has value "test", x4 has value "updated"
在以下情况下,"ok2" 的值是多少(因此,"ref" 的值是多少)。
- x2 和 x3 是同一个引用,即 x2 == x3
- 它们不是,即 x2 != x3(但是 x2.equals(x3))
我的理解是,在场景2中,更新会失败,即ok2为false。
如果我的理解是正确的,那么以价值平等重现这种行为的最佳方式是什么?换句话说,您将如何设置一个适用于字符串相等性的原子 compareAndSet 操作(即在两种情况下有效 ok==true)?
谢谢
您可以通过循环执行此操作,方法是提取值、比较然后更新,除非值在提取和尝试更新之间发生变化:
static <T> boolean setIfEqualTo(AtomicReference<T> ref, T old, T value) {
T current;
do {
current = ref.get();
if (!Objects.equals(current, old)) {
// They're not equal, so give up on trying to update.
return false;
}
} while (
// Try to update, if the value is still equal to `current`.
!ref.compareAndSet(current, value));
return true;
}
除非竞争激烈,否则不会循环,或者可能会循环一次(如果你不走运)或两次(如果你真的很不走运)。