Why is volatile needed if synchronized exists? Synchronized covers all cases of volatile.
sobes.tech AI
Answer from AI
The key difference between volatile and synchronized in Java is the level and purpose of synchronization.
volatile guarantees visibility of changes to a variable across threads: when one thread modifies a volatile variable, other threads immediately see this change. It is a lightweight mechanism that does not block threads and does not ensure atomicity of operations.
synchronized, on the other hand, provides mutual exclusion (a monitor), meaning it blocks access to code or an object, ensuring that only one thread executes a critical section at a time. Additionally, synchronized also guarantees visibility of changes (through entering and exiting the monitor).
Thus, volatile is suitable for simple cases where only visibility of changes is needed (e.g., a termination flag), without the need for locks and atomic operations. synchronized is necessary when comprehensive synchronization is required, including atomicity and execution order.
Example of using volatile:
private volatile boolean running = true;
public void stop() {
running = false; // change is immediately visible to other threads
}
public void run() {
while (running) {
// work
}
}
Here, volatile is sufficient to stop the thread without locks.