AtomicInteger.incrementAndGet线程安全吗? [英] Is AtomicInteger.incrementAndGet thread safe?
问题描述
例如,如果我在多个线程中运行此代码并且每个线程多次运行,是否会发生数据争用?
For example, if I run this code from multiple threads and each thread for many times, will there be potentially a data race?
public boolean swap(int i, int j) {
if (value.get(i) <= 0 || value.get(j) >= maxval) {
return false;
}
value.decrementAndGet(i);
value.incrementAndGet(j);
return true;
}
顺便说一句,如果我在这里使用decrementAndGet或getAndDecrement有什么区别吗?
BTW, is there any difference if I use decrementAndGet or getAndDecrement here?
值是一个AtomicIntegerArray.我需要在不同的同步方法之间进行性能测试.因此,我交换了elemtents的值,看看输出的总和是否与预期的相同
value here is an AtomicIntegerArray. I need to do performance test among different synchronization method. So I swap elemtents in value and see if the output sum the same to what is expected
我的任务是找到一种不应为DRF"但仍必须无死锁"的方法,并且该方法也比ReentrantLock快得多.所以我很难找到一种具有数据竞争的方法...
My task is to find a method that "should not be DRF," but "must still be deadlock-free", and is also much faster than ReentrantLock. So I'm troubling with finding a method that has data race...
推荐答案
是的,incrementAndGet
是线程安全的.
incrementAndGet
和getAndIncrement
与++i
和i++
相同.即
int i = 0;
i++ // <- expression returns 0, i is now 1
++i // <- expression return 2, i is now 2
Ditto与decrement
.
但是,您在if
中的||
上两次调用get
时,您的代码不是不是线程安全的.因此,无论value
是什么,都可以在value.get(i)
和value.get(j)
之间更改 值.
Your code, however, is not threadsafe as you call get
twice across the ||
in the if
. So the value could be changed between value.get(i)
and value.get(j)
, whatever value
is.
这篇关于AtomicInteger.incrementAndGet线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!