So I have lot of asyn threads running concurrently. Now when any of the jobs fail, I set boolean job failed flag to true. That would indicate that one of the sub tasks has failed. Can I use static boolean variable instead of Java concurrent atomic boolean and still achieve the same functionality?
-
1`static` means shared across all instances. It doesn't have anything to do with thread safety or atomcity. – Peter Lawrey Jun 17 '16 at 18:42
4 Answers
Can I use static boolean variable instead of Java concurrent atomic boolean and still achieve the same functionality?
No! Static means Something completely different to Atomic
if you define this
static boolean staticFlag;
in a class Foo, then staticFlag is a variable that belongs the class and not the instances of the class...
so if you do Foo.staticFlag = true
, ALL the instances of the class Foo will be affected by that change..
on the other hand..
if multiple threads are accessing a same boolean then you have a race condition ant there you can use a AtomicBoolean to prevent synch issues...

- 47,427
- 17
- 69
- 97
As far as I understand, you "just" want to set a global state to true, if one of many threads failes to do something. Yes you can do that with a static boolean, but you should declare it volatile.
In my world you can do that, because non of your threads will ever access that boolean for comparison etc. If they access it, they will set it to true. They will not care which value the boolean has. No thread will ever set it to false.

- 563
- 5
- 17
-
1But another thread will need to read it so that it's not `false` and there you have your problem. You need to declare it volatile in that case. – John Vint Jun 17 '16 at 21:23
-
If you set it to `volatile`, it wouldn't matter if the value were changed multiple times. However, the basic answer is correct: a `static volatile boolean` is what he wants. – Warren Dew Jun 17 '16 at 22:34
The Main difference is Thread-Safety, AtomicBoolean is Thread-Safe, while boolean variable is not Thread-Safe, regardless if its static or not . static variable means its a Class variable rather than instance variable . see Oracle class variable
To answer your question
If you are accessing(read/write) your flag from different threads(which you probably do), use AtomicBoolean, otherwise use standard boolean is enough. But i would recommend to use the AtomicBoolean
, since you are dealing with few threads that writes to the flag, and one other thread may read it.
A Second Option to secure your Thread-Safety by using volatile
keyword like other answers stated
public static volatile myFlag = false;
will garenty Thread-Safety

- 1
- 1

- 326
- 3
- 16