`volatile` guarantees visibility (and ordering) of a variable between threads, but doesn’t make compound operations atomic. `synchronized` provides mutual exclusion and also establishes happens-before (visibility) for the protected code.
class StopFlag {
private volatile boolean stop = false;
void requestStop() {
stop = true;
}
void runLoop() {
while (!stop) {
// do work
}
}
}