以原子方式更新多个volatile和j.u.c.atomic变量 [英] Atomically update multiple volatile and j.u.c.atomic variables
问题描述
为了原子地更新两个和更多的volatile变量,是否需要通过同步,reentrantReadWriteLock等锁来保护它?
In order to atomically update two and more volatile variables does it need to be guarded by lock with synchronized, reentrantReadWriteLock etc?
即
volatile int vVar1, vVar1; // or AtomicInteger
/*** Needs to be updated atomically ***/
void atomicUpdate(int var1, int var2){
vVar1 = var1;
vVar2 = var2;
}
相同的代码用于java.util.concurrent.atomic变量.
The same code is for java.util.concurrent.atomic variables.
推荐答案
如果您需要自动分配两个值,将volatile int
更改为AtomicInteger
不会解决您的比赛条件问题.
If you need to assign two values atomically, chaning volatile int
to AtomicInteger
will not solve your race condition problem.
要解决您的问题,您基本上有两种选择:
To solve your issue, you basically have two options:
- 让方法更新变量
synchronized
(也许也读取这些变量的方法) - 为两个变量创建一个包装器,并利用赋值是原子操作这一事实
- Make the methods updating the variables
synchronized
(and maybe the methods reading those variables too) - Create an wrapper for your two variables, and make use of the fact that assignment is an atomic operation
选项2的示例:
volatile Vars vars;
void atomicUpdate(int var1, int var2) {
vars = new Vars(var1, var2);
}
public static Vars {
private int vVar1; // volatile if they need to be modified
private int vVar2;
}
我更喜欢选项2,因为它是非阻塞的,并且允许您缓存任何类型的数据.
I largely prefer option 2 since it is non blocking and allows you to cache any type of data.
这篇关于以原子方式更新多个volatile和j.u.c.atomic变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!