# synchronized vs volatile: Visibility, Atomicity and Ordering

> What is the difference between synchronized and volatile? When is volatile enough, and why is count++ not thread-safe even on a volatile field?

Canonical: https://www.internhack.in/learn/interview/java-interview/java-synchronized-volatile
Last updated: 2026-11-28

Difficulty: Advanced

## Question

What is the difference between synchronized and volatile? When is volatile enough, and why is count++ not thread-safe even on a volatile field?

## Answer

To answer this well you need to understand that concurrency bugs come from three separate problems, and synchronized and volatile solve different subsets of them. Let me define them first, because that framework will carry you through any follow-up.

The three problems are atomicity, visibility and ordering. Atomicity means an operation happens as one indivisible step. Visibility means that when one thread writes a value, other threads actually see it. Ordering means that instructions are not observed out of sequence. The last two exist because each CPU core has its own caches and registers, and both the compiler and the CPU are allowed to reorder instructions for speed. The Java Memory Model (JMM) defines when a write by one thread is guaranteed to be visible to another, through a set of happens-before rules.

The keyword synchronized provides mutual exclusion plus visibility. Only one thread at a time can hold the monitor of a given object and run the guarded block, which gives atomicity for the whole block. And when a thread exits the block (releases the monitor), all its writes are flushed; the next thread that acquires the same monitor sees them. So synchronized handles atomicity, visibility and ordering, at the cost of possible blocking. It can be applied to an instance method (locks this), a static method (locks the Class object) or a block on any object, which is preferred because it narrows the critical section. Synchronized is reentrant: the same thread can reacquire a lock it already holds.

The keyword volatile applies to a field and provides only visibility and ordering. A write to a volatile variable is immediately visible to all threads, and a read always sees the latest write. It also forbids certain reorderings around the access, establishing a happens-before edge between the write and subsequent reads. But volatile does not make compound actions atomic and does not lock anything.

That explains the famous trap. count++ looks like one step, but it is really three: read count, add one, write back. If two threads do this at once, both may read 5 and both write 6, losing an update. Making count volatile guarantees each read sees the latest value, but the read-modify-write sequence can still interleave. To fix it, use synchronized, an AtomicInteger (lock-free using compare-and-swap) or a LongAdder for high contention counters.

When is volatile enough? For a simple flag written by one thread and read by others, such as volatile boolean running used to stop a worker loop. Without volatile, the JIT may hoist the read out of the loop and the worker never sees the change, spinning forever. Volatile is also essential in double-checked locking singletons: the instance field must be volatile, otherwise another thread could see a partially constructed object due to reordering.

Other facts: volatile on long and double also guarantees atomic 64-bit reads and writes. Declaring an object reference volatile does not make its internal fields safe. The rule of thumb: use volatile for independent state flags, use synchronized or java.util.concurrent for invariants involving several variables or check-then-act logic.

Compare cost: volatile is cheaper than locking because it never blocks, but do not sprinkle it everywhere hoping to cure races.

## Code examples

### volatile stop flag

```
public class VolatileFlag {
    static volatile boolean running = true;

    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(() -> {
            long n = 0;
            while (running) {
                n++;
            }
            System.out.println("Stopped");
        });
        worker.start();
        Thread.sleep(100);
        running = false;
        worker.join();
    }
}
```

Because running is volatile, the write from main becomes visible to the worker. Without volatile the loop could spin forever.

### Fixing a lost-update race

```
import java.util.concurrent.atomic.AtomicInteger;

public class CounterDemo {
    static int plain = 0;
    static AtomicInteger atomic = new AtomicInteger();
    static final Object LOCK = new Object();

    public static void main(String[] args) throws InterruptedException {
        Runnable task = () -> {
            for (int i = 0; i < 10000; i++) {
                synchronized (LOCK) {
                    plain++;
                }
                atomic.incrementAndGet();
            }
        };
        Thread a = new Thread(task);
        Thread b = new Thread(task);
        a.start();
        b.start();
        a.join();
        b.join();
        System.out.println(plain + " " + atomic.get());
    }
}
```

Both the synchronized block and the AtomicInteger make the increment atomic. A plain or merely volatile int would usually print less than 20000.

## Key points

- Atomicity, visibility and ordering are the three concerns of thread safety.
- synchronized gives mutual exclusion plus visibility; volatile gives visibility and ordering only.
- count++ is read-modify-write, so volatile alone does not make it safe.
- Use volatile for simple flags and safe publication in double-checked locking.
- AtomicInteger and LongAdder provide lock-free counters.

## Common follow-up questions

- Why must the singleton instance be volatile in double-checked locking?
- What is the happens-before relationship?
- What is the difference between synchronized method and synchronized block?
- What is a ReentrantLock and how does it differ from synchronized?

## Interview tips

- Open with atomicity, visibility, ordering. That framework organizes the entire answer.
- Give the stop-flag as the good use of volatile and count++ as the bad one.

## Concepts covered

synchronized, volatile, Java Memory Model, Atomicity, happens-before

Previous: [Thread vs Runnable and the Thread Lifecycle](https://www.internhack.in/learn/interview/java-interview/java-thread-vs-runnable) · Next: [wait(), notify() and the Producer-Consumer Pattern](https://www.internhack.in/learn/interview/java-interview/java-wait-notify) · [All of Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)

## More Core Java & Collections questions

- [Deadlock: Conditions, Detection and Prevention](https://www.internhack.in/learn/interview/java-interview/java-deadlock)
- [ExecutorService, Thread Pools and Future](https://www.internhack.in/learn/interview/java-interview/java-executorservice-thread-pools)
- [Lambdas, Functional Interfaces and Method References](https://www.internhack.in/learn/interview/java-interview/java-lambdas-functional-interfaces)
- [Streams API: Pipelines, Laziness and Collectors](https://www.internhack.in/learn/interview/java-interview/java-streams-api)
- [Optional: Purpose, Usage and Anti-Patterns](https://www.internhack.in/learn/interview/java-interview/java-optional)
- [Records in Java: Concise Immutable Data Carriers](https://www.internhack.in/learn/interview/java-interview/java-records)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)
