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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With