Interview Q&A / Java

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What does the volatile keyword do in Java, and does it make count++ safe?

SHORT ANSWER

volatile guarantees that a write by one thread is immediately visible to other threads and prevents certain reordering. It does not make compound actions like count++ atomic, so a counter still needs synchronized or AtomicInteger.

Explain it simply

Picture a notice board in the hostel. Normally each student may keep a private photocopy of the notice and never check for updates. volatile forces everybody to read from the real board each time, so a change is seen by all. But reading the board and writing a new number back is still two separate steps, and two students can interleave them.

Example

java
class Worker implements Runnable {
    private volatile boolean running = true;     // visible across threads

    public void run() {
        while (running) { /* do work */ }
        System.out.println("stopped");
    }
    void stop() { running = false; }             // other thread's write is seen
}

class BadCounter {
    volatile int count = 0;
    void inc() { count++; }    // read, add, write: not atomic, updates can be lost
}

What to say in the interview

"volatile gives visibility and ordering, not atomicity. It is right for a simple status flag written by one thread and read by others. For count++ I need AtomicInteger or a synchronized block, because the increment is three steps: read, add, write. Without volatile, a thread may keep a stale cached copy and a loop may never see the stop flag change."

Common mistakes

  • Using volatile on a counter and assuming it is thread-safe.
  • Thinking volatile makes a whole object's fields volatile. It applies to the reference only.

#java#multithreading#volatile

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.