Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Is there a right way to use static volatile variables?

I want to have a flag that could be accessible to read/write from different threads without any problem of dirty values. Is it enough to make it static volatile?

static volatile boolean flag;
like image 956
Winte Winte Avatar asked Feb 19 '23 12:02

Winte Winte


1 Answers

No, this is not enough if you need an action like this:

volatile int v = 0;

Thread 1:
v++;

Thread 2:
v--;

Ideally you want v=0 when you execute the above code, but this is what is really happening (a composite action):

Thread 1:
r1 = v;
r2 = r1 + 1;
v = r2;

Thread 2:
r3 = v;
r4 = r3 - 1;
v = r4;

And both the threads will give values of 1 and -1 respectively. Source: Volatile Does Not Mean Atomic!

If you need guaranteed consistent result in a mulithreaded scenario, you should be using Atomic classes in Java as @Eng.Fouad pointed out.

In the case of a boolean too, compare-and-set will be helpful from AtomicBoolean class than using volatile.

like image 192
zengr Avatar answered Feb 21 '23 01:02

zengr