Java – update multiple volatile and j.u.c.atomic variables atomically

In order to update two or more volatile variables atomically, do you need to protect them through lock with synchronized, reentrantreadwritelock, etc?

Namely

volatile int vVar1,vVar1; // or AtomicInteger

/*** Needs to be updated atomically ***/
void atomicUpdate(int var1,int var2){
  vVar1 = var1;
  vVar2 = var2;
}

java. util. concurrent. The code of atomic variable is the same

Solution

If you need to assign two values atomically, converting volatile int to atomicinteger will not solve your race condition problem

To solve your problem, you basically have two choices:

>Synchronize method update variables (perhaps the method that reads them) > create a wrapper for two variables and take advantage of the fact that assignment is an atomic operation

Example of option 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;
}

I like option 2 because it is non - blocking and allows you to cache any type of data

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>