英文:
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<String> atomicReference = new AtomicReference<>("abc");
I have 2 threads executing code:
Thread 1: atomicReference.compareAndSet("abc", "def")
Thread 2: atomicReference.compareAndSet("abc", "efg")
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论