0

In a book on programming I read:

For “infinite” loops, there should be some way to tell the thread that it is no longer needed, such as via an AtomicBoolean flag

What if instead of AtomicBoolean it had had volatile boolean? What negative efects are eliminated by having AtomicBoolean as opposed to volatile boolean for the case above?

If we use the variable exclusively as a flag for thread termination, is there still a difference between AtomicBoolean and volatile boolean?

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158

3 Answers3

2

It depends on the specific implementation details of your loop and the external event setting said stop flag. In practice volatile is sufficient if you can ensure that there is only one thread updating the volatile. Example:

volatile boolean alive = true;

void loop() {
     while (alive) {
     }
}

void stop() {
    alive = false;
}

Thats perfectly fine, since there is only one possible state transition from true to false.

As soon as is gets a little more complicated (e.g. AtomicInteger reflecting the loops state) you will need compareAndSet() style operations to properly implement the state transitions of the variable.

Example:

volatile int state = NOT_STARTED;

void loop() {
    state = RUNNING;
    while (state == RUNNING) {
    }
    state = TERMINATED;
}

void stop() {
    state = ABORT;
}

This would possibly miss a stop signal if stop() is called before "state = RUNNING" executes, so here compareAndSet is needed to avoid accidentially overwriting ABORT with RUNNING.

Durandal
  • 19,919
  • 4
  • 36
  • 70
1

I think compare-and-set and getAndSet operation isn't atomic with volatile variables. Also check the description given by teto here

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 1
    Indeed, I don't see the requirement of an atomic compare-and-set operation when used as a flag that should stop a loop on a different thread, if the case is ThreadA that should stop ThreadB. – Jack May 08 '14 at 14:41
1

using a AtomicBoolean all read and write actions are atomic (as the name includes). with a volatile boolean you still have to deal with race conditions, when two threads accessing the variable at the same time.

Simulant
  • 19,190
  • 8
  • 63
  • 98
  • If I'm only using that flag to set/determine thread termination condition, is there still a difference? – Alexander Kulyakhtin May 08 '14 at 15:01
  • 2
    if only one Thread at a time is writing to it and it is okay to maybe finish one interation later, you will have no problems using a `volatile boolean`. – Simulant May 08 '14 at 16:10