0

I have one thread that runs periodically every 5 minutes, it may change the value of a flag and many threads reads that flag. Please suggest if the following design has any issues. I choose volatile so every thread gets correct value of flag and no caching. I do not see AtomicBoolean makes much sense here.

Class A {
 private static volatile boolean flag = false;

 //Calls every 5 minutes
 //Value of this flag may change every 5 minutes by thread. 
 checkAndSetFlag(boolean newFlag) {
   flag= newFlag;
 }
}

A number of threads will just check the value as follows. I have no issue if some threads reads the old value at the same time the value is changing.

Class B {
  doSomething() {
    if(A.flag) {
      doSomethingElse();
    } 
  }
}
Chinku T
  • 3
  • 2
  • This is not an exact duplicate. The proposed dupe has a scenario with many writer threads and a single reader whereas in this question it's vice versa. These subtle differences are significant in multithreading questions. – Mick Mnemonic Oct 01 '15 at 02:18

1 Answers1

0

AtomicBoolean and volatile have the exact same semantics in your usage (single writer), so either will work. The case for AtomicBoolean (or any Atomic class) is when you have to deal with multiple potential writers.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
  • Thanks. Do you suggest any other materials other than Brian Goetz's Concurrency in practice. Any discussion forums where I can discuss these kinds of questions? – Chinku T Oct 08 '15 at 22:27
  • sorry, don't know any good online forums for advanced topics like that. concurrency in practice is awesome of course. – jtahlborn Oct 09 '15 at 01:09