iinc在Java中是原子的吗? [英] Is iinc atomic in Java?
本文介绍了iinc在Java中是原子的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道在没有锁定的情况下,增量操作在C ++中不是原子的.
JVM会在其iinc
指令的实现中添加任何锁吗?
解决方案
没有它不是
- 获取c的当前值.
- 将检索到的值增加1.
- 将增量值存储回c中.
为了线程安全,您需要使用synchronized
关键字或使用AtomicXXX
方法.
更新:
public synchronized void increment() {
c++;
}
或
AtomicInteger integer = new AtomicInteger(1);
//somewhere else in code
integer.incrementAndGet();
也请阅读: Java中的ininc原子吗? >
I know increment operation is not atomic in C++ without locking.
Will JVM add any lock on its implementation of iinc
instruction?
解决方案
No its not
- Retrieve the current value of c.
- Increment the retrieved value by 1.
- Store the incremented value back in c.
Java Documentation for Atomicity and Thread Interference
You need to either use synchronized
keyword or use AtomicXXX
methods for Thread safety.
UPDATE:
public synchronized void increment() {
c++;
}
or
AtomicInteger integer = new AtomicInteger(1);
//somewhere else in code
integer.incrementAndGet();
Also read: Is iinc atomic in Java?
这篇关于iinc在Java中是原子的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文