Thursday, February 26, 2026

What is volatile Keyword in Java?

The volatile keyword in Java is used to ensure visibility of changes to variables across multiple threads. It tells the JVM that a variable’s value may be modified by different threads, so it should always be read from main memory, not from a thread’s local cache.


 volatile Keyword in Java

🔹 Why do we need volatile?

In multithreading, each thread can keep a local copy of variables in its CPU cache.
This may cause inconsistent data when one thread updates a variable but other threads still see the old value.

👉 volatile solves this visibility problem.


🔹 Example Without volatile

class Test {
    static boolean flag = true;

    public static void main(String[] args) {
        new Thread(() -> {
            while(flag) {
                // loop runs forever
            }
            System.out.println("Stopped");
        }).start();

        flag = false;
    }
}

❌ Problem:

  • The thread may never stop because it reads cached value true.


🔹 Example With volatile

class Test {
    static volatile boolean flag = true;

    public static void main(String[] args) {
        new Thread(() -> {
            while(flag) {
            }
            System.out.println("Stopped");
        }).start();

        flag = false;
    }
}

✅ Now:

  • Every read happens from main memory

  • Thread immediately sees updated value.


🔹 Key Features of volatile

✔ Guarantees visibility between threads
✔ Prevents instruction reordering (partial ordering guarantee)
✔ Lightweight compared to synchronization
❌ Does NOT provide mutual exclusion (no locking)


🔹 volatile vs synchronized






🔹 When to Use volatile

✅ Status flags (stop/start signals)
✅ Configuration variables
✅ One writer, multiple readers scenario

❌ Avoid when:

  • Multiple operations must be atomic (increment, decrement, etc.)


🔹 Important Interview Point

volatile ensures visibility, not thread safety.

Example:

volatile int count = 0;
count++;   // NOT thread-safe

Because increment involves multiple steps (read → modify → write).


🚀 Learn Advanced Java Memory & Multithreading with Real Projects

If you want practical JVM, GC, and multithreading concepts with industry examples, explore Best Java Real Time Projects Online Training in ammerpet

No comments:

Post a Comment

To build frictionless production-ready Java applications in 2026, developers must move beyond traditional coding styles and adopt modern pra...