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;
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.
It's tempting but avoid code like that.
In a simple scenario, this seems to works because boolean
doesn't allow any math operations (you can only assign values to it). But you rarely have simple cases. Eventually, you will need
if(flag) {
flag = false;
}
and this code will sometimes break. Therefore, as suggested by the other answers, you should use the java.util.concurrent.Atomic
* classes.