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.
AtomicBoolean vs volatile [duplicate]
题
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
?
解决方案 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.
I think compare-and-set and getAndSet operation isn't atomic with volatile variables. Also check the description given by teto here