在Java的原子compareAndSet方法中是否有锁定?

huangapple go评论73阅读模式
英文:

Is there locking in the Atomic compareAndSet method in Java?

问题

如果我有类似以下的代码:

AtomicReference<String> atomicReference = new AtomicReference<>("abc");

我有两个线程执行代码:

线程 1: atomicReference.compareAndSet("abc", "def")

线程 2: atomicReference.compareAndSet("abc", "efg")

是否可能出现这样的情况,两个线程同时执行并找到了之前声明的值 "abc",然后两者都执行了这个方法?
或者如果一个线程执行了compareAndSet,另一个线程是否必须等待直到它完成(基本上是一种锁定机制)?

英文:

If I have something like:

AtomicReference&lt;String&gt; atomicReference = new AtomicReference&lt;&gt;(&quot;abc&quot;);

I have 2 threads executing code:

Thread 1: atomicReference.compareAndSet(&quot;abc&quot;, &quot;def&quot;)

Thread 2: atomicReference.compareAndSet(&quot;abc&quot;, &quot;efg&quot;)

Could there be a case where both threads exceute this at same time and find the value "abc" which was declared and both executes the method
or if one thread exceutes compareandset other will have to wait until it completes (basically some kind of locking mechanism)?

答案1

得分: 1

一般来说,合理的实现不会在原子的compareAndSet操作中使用锁。一些旧的/非常低端的32位架构可能会在AtomicLong的操作中使用锁。

方法体可能(某些架构下)允许多个线程同时执行,但只有一个可以成功。

英文:

In general, reasonable implementation will not use a lock for atomic compareAndSet. Some old/very low-end 32-bit architectures may use a lock for AtomicLong.

The method bodies may (some architectures) allow execution by more than one thread at a time, but only one can succeed.

答案2

得分: 0

也许两个线程可以同时执行。但总会只有一个“赢家”,只有一个会成功。

英文:

Maybe it can happen that both threads execute at the same time. But there is always just one "winner", just one will succeed.

答案3

得分: -1

来自文档:

包 java.util.concurrent.atomic

一个小工具包,支持在单个变量上进行无锁线程安全编程。

英文:

From the documentation:

> Package java.util.concurrent.atomic
>
> A small toolkit of classes that support lock-free thread-safe programming on single variables.

huangapple
  • 本文由 发表于 2020年4月6日 02:58:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/61047870.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定