← Back to list

Understanding the “volatile” keyword in Java in 1 minute

“volatile” is a non-access modifier used for variables that are shared among multiple threads. => variable modifier

Chamlini Dayathilake · 2025-01-31 12:24 · 70 claps · 1.1 min read
#volatile #java #java-thread #java-thread-safety #multithreading
Open on Medium ↗
Wiki topics: SAF · Safety & Alignment 📚 · Books & Reading

Understanding the “volatile” keyword in Java in 1 minute

“volatile” is a non-access modifier used for variables that are shared among multiple threads. => variable modifier

It is used to ensure a variable is ALWAYS read from and written to main memory. => Ensure VISIBILITY

This prevents using the cashed values in thread local memory, which may lead to stale or inconsistent data.

Key points:

  • Ensure VISIBILITY — changes made by one thread are immediately visible to other threads
  • Prevents instruction re-ordering — avoid unexpected execution order due to compiler optimizations
  • Useful for FLAGS — ideal for stopping threads
  • “volatile” is NOT thread safe and does NOT prevent race conditions.
  • It does NOT guarantee atomicity. Use synchronized or atomic variables for atomic operations.

[The above two will be explained in detail in a future story.]

  • The performance is good comparably since it doesn’t use locks.
  • Not needed for immutable objects or local variables since they are inherently thread-safe.
  • Great for flags, status variables, or simple shared variables via multithreading.

The following is a simple example of usage of “volatile” in a code implementation.

class Example {
    private static volatile boolean flag = false; // Ensures visibility

    public static void main(String[] args) {
        new Thread(() -> {
            while (!flag) {} // Always reads the latest value
            System.out.println("Flag changed!");
        }).start();

        try { Thread.sleep(1000); } catch (InterruptedException e) {}

        flag = true; // Change is now visible to all threads
    }
}

Hope this helped!

Let’s meet in another story.


메타데이터
post_id
e1b68773c8dc
slug
understanding-the-volatile-keyword-in-java-in-1-minute-e1b68773c8dc
url
https://medium.com/@chamlinid/understanding-the-volatile-keyword-in-java-in-1-minute-e1b68773c8dc
canonical_url
https://medium.com/@chamlinid/understanding-the-volatile-keyword-in-java-in-1-minute-e1b68773c8dc
author_url
https://medium.com/@chamlinid
status
ok
fetched_at
2026-07-09 00:50:33