【问题标题】:Which AtomicInteger methods are test-and-set, fetch-and-add and compare-and-swap (in terms of lock-free algorithms)?哪些 AtomicInteger 方法是 test-and-set、fetch-and-add 和 compare-and-swap(就无锁算法而言)?
【发布时间】:2019-09-07 09:39:36
【问题描述】:

CAS(比较和交换):boolean compareAndSet(int expect, int update)

FAA(获取并添加) : int addAndGet(int delta) ???

TAS (test-and-set) : ???

据我了解:

CAS (compare-and-swap) “同步”(无锁,在 CPU 指令级别)代码如下:

if(a==b) {
  a++;  // or a = a + 7;
}

FAA (fetch-and-add):“同步”(无锁,在 CPU 指令级别)代码如下:

x = x + 7;

但我不确定“测试和设置”与哪种代码相关。

【问题讨论】:

    标签: java concurrency atomic lock-free atomicinteger


    【解决方案1】:

    Test-and-set 是一个原子 RMW 操作,它将内存位置的值设置为 1 并返回旧值(10)。

    Java 中没有“真正的”测试和设置操作,但您可以通过将1 传递给AtomicInteger::getAndSet 并期望它返回10 来模拟它。或者,您可以通过将true 传递给AtomicBoolean::getAndSet 并期望truefalse 来模拟TAS。

    在您提供的增加变量的示例中,它不是很有用,因为 TAS 是二进制操作。

    【讨论】:

      猜你喜欢
      • 2022-09-25
      • 2020-06-11
      • 2022-12-04
      • 2022-12-27
      • 1970-01-01
      • 2013-07-30
      • 2014-05-16
      • 1970-01-01
      • 2016-11-09
      相关资源
      最近更新 更多