What is the difference between synchronized and volatile in Java?

Pointsynchronizedvolatile
Applies toMethods and blocksVariables
Mutual exclusionYes (one thread at a time)No
Visibility of changesYesYes
Atomic count++Yes, inside a synchronized blockNo
CostHigher (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.