AtomicReference compareAndSet:字符串引用与值相等

问题描述 投票:1回答:1

假设您有:

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”的值是什么。

  1. x2和x3是一个相同的参考,即x2 == x3
  2. 不是,即x2!= x3(但x2.equals(x3))

我的理解是,在方案2中,更新将失败,即ok2为false。

如果我的理解是正确的,那么用价值平等再现这种行为的最佳方法是什么?换句话说,您将如何设置一个在字符串相等性上起作用的原子compareAndSet操作(即,在两种情况下都有效ok == true)?

谢谢

java atomic atomicity
1个回答
2
投票

您可以通过循环来执行此操作,方法是提取值,进行比较,然后更新,除非值在提取和尝试更新之间发生变化:

© www.soinside.com 2019 - 2024. All rights reserved.