What is the difference between synchronized and volatile in Java?
| Point | synchronized | volatile |
|---|---|---|
| Applies to | Methods and blocks | Variables |
| Mutual exclusion | Yes (one thread at a time) | No |
| Visibility of changes | Yes | Yes |
Atomic count++ | Yes, inside a synchronized block | No |
| Cost | Higher (locking) | Low |
Use volatile for a simple flag which one thread writes and others read. Use synchronized, a Lock or AtomicInteger when several steps must be done together.
public class Main {
static volatile boolean running = true;
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
long loops = 0;
while (running) {
loops++;
}
System.out.println("Worker stopped");
});
worker.start();
Thread.sleep(200);
running = false; // the worker sees this change because of volatile
worker.join();
}
}
Output
Worker stopped
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |