简体   繁体   English

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;
}

BTW, is there any difference if I use decrementAndGet or getAndDecrement here? 顺便说一下,如果我在这里使用decrementAndGet或getAndDecrement有什么区别吗?

value here is an AtomicIntegerArray. 这里的值是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 所以我在值中交换elemtents,看看输出总和是否与预期相同

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. 我的任务是找到一个“不应该是DRF”但“必须仍然无死锁”的方法,并且比ReentrantLock快得多。 So I'm troubling with finding a method that has data race... 所以我很难找到一种有数据竞争的方法......

Yes, the incrementAndGet is thread safe. 是的, incrementAndGet是线程安全的。

incrementAndGet and getAndIncrement are the same as ++i vs i++ . incrementAndGetgetAndIncrement++i vs i++ Ie

int i = 0;
i++ // <- expression returns 0, i is now 1
++i // <- expression return 2, i is now 2

Ditto with decrement . decrement同上。

Your code, however, is not threadsafe as you call get twice across the || 您的代码,但是,是不是线程安全的您拨打get跨越两次|| in the if . if So the value could be changed between value.get(i) and value.get(j) , whatever value is. 所以值可以value.get(i)value.get(j)之间改变,无论value是什么。

As written above, all methods of AtomicInteger is thread-safe. 如上所述, AtomicInteger所有方法都是线程安全的。

will there be potentially a data race 会不会有数据竞争

Technically yes, there will be a data race, because 技术上是的,会有数据竞争,因为

  • You call get twice while evaluating logical expression; 在评估逻辑表达式时调用get两次;
  • Saying " AtomicInteger is thread-safe" means that each thread calling for example value.decrementAndGet(i) (and all other CAS-based methods) will eventually complete this operation succefully. AtomicInteger是线程安全的”意味着每个调用例如value.decrementAndGet(i) (以及所有其他基于CAS的方法)的线程最终将成功完成此操作。 No other guarantees . 没有其他保证

Using thread-safe class is not enough for preventing data races. 使用线程安全类不足以防止数据争用。 Also I'd like to mention that data race is not always bad thing, sometimes it is acceptable actually. 另外我想提一下数据竞争并不总是坏事,有时它实际上是可以接受的。

Yes; 是; all of the methods on the Atomic* classes are thread-safe. Atomic*类的所有方法都是线程安全的。

The difference between decrementAndGet() and getAndDecrement() is which value it returns. decrementAndGet()getAndDecrement()之间的区别在于它返回的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM