What does the volatile keyword guarantee, and what does it NOT?
Reviewed by Gurusankar M.
β‘ Short Answer
volatile guarantees visibility (every read sees the latest write) and ordering (no reordering across the access) via happens-before. It does NOT make compound operations like count++ atomic β for that use Atomic classes or locks.
βCoffee Chat Question
Concept Made Simple
βWhat does the volatile keyword guarantee, and what does it NOT?β
π§ Mind Map Answer
Remember It Faster
β¨οΈHands-on Keyboard
Learn by Doing
private volatile boolean running = true; // visible to all threads
public void stop() { running = false; }
public void loop() { while (running) { /* ... */ } }π₯What If?
Think Beyond the Expected
A worker loop never stops after you flip a non-volatile boolean from another thread β why?
Without volatile, the JVM/JIT may cache the flag in a register, so the worker never sees the update β it loops forever. Marking the flag volatile forces a fresh read from main memory each iteration.
πReal World
The volatile stop-flag is the canonical fix for 'my background thread won't shut down'; misusing volatile for counters (count++) is a classic lost-update bug.
π―Interviewer's Expectation
Keywords they're listening for:
β οΈCommon Mistakes
- βUsing volatile for count++ (not atomic)
- βAssuming volatile is a substitute for locking
- βForgetting volatile on a cross-thread flag
β Best Practices
- βvolatile for flags / single-writer publication
- βAtomic*/locks for read-modify-write
- βReason in terms of happens-before
πFollow-up Questions
- 1Why isn't volatile enough for a counter?
- 2What is the happens-before relationship?
- 3How does volatile enable safe publication?
π§©Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly β AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: volatile & Memory Model (Multithreading) Interview question: "What does the volatile keyword guarantee, and what does it NOT?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
β Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission β at no extra cost to you. It helps keep Full Stack Interview Guru free.