4

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;
dda
  • 6,030
  • 2
  • 25
  • 34
Winte Winte
  • 753
  • 5
  • 11
  • 24
  • 2
    I am not sure if it is enough or not, but I recommend to use [`AtomicBoolean`](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicBoolean.html) instead. – Eng.Fouad Nov 14 '12 at 08:08
  • I would avoid static mutable fields whenever possible. Instead I would use an AtomicBoolean which is passed to the threads you want to flag. – Peter Lawrey Nov 14 '12 at 08:49

2 Answers2

5

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.

zengr
  • 38,346
  • 37
  • 130
  • 192
  • Yes, it is for operations that read, calucalte and save data. But is it correct to use for only read\write operations as boolean vars? – Winte Winte Nov 14 '12 at 08:31
  • I didn't get that. Are you asking is volatile correct to use for r/w ops? (I just answered that) – zengr Nov 14 '12 at 08:33
  • No, I mean that we have static volatile flag. Then I mark it as false, another thread read it, and other thread marks it as true. In this case will I get a dirty values or not? – Winte Winte Nov 14 '12 at 08:36
  • ah, I see. Well, volatile will work, but you will need to make sure that you are the owner and its modification is limited to 1 thread (Example, a flag like shutdownthissystem can be volatile). But if you have a flag which can modified by any thread at random and read again by some other thread, you should be using AtomicBoolean. – zengr Nov 14 '12 at 08:48
3

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.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820