Interview Question

What is volatile?

volatile provides visibility and ordering for a field, not general atomicity.

💡 Concept ✅ Quick Revision ☕ Java

Answer

A volatile field has special visibility and ordering semantics under the Java Memory Model. • A write to a volatile field happens-before every subsequent read of that field. • Volatile does not make compound actions such as count++ atomic. • Use locks or atomic classes when several operations must act as one unit.

Example

Code
class Task {
    private volatile boolean stopped;
    void stop() { stopped = true; }
}

Quick Revision

volatile provides visibility and ordering for a field, not general atomicity.