Volatile Keyword in Java

volatile Keyword in Java: Usage & Examples

April 6th, 2026
1083
15:00 Minutes

The volatile keyword in Java indicates that different threads may modify a variable value. It ensures that changes to a variable are always visible to other threads. This behavior prevents issues caused by thread local caching. When I was working with Java multithreading in my projects, I used the volatile keyword to solve visibility problems.

In this blog, I will explain what the volatile keyword means with some examples.

Let’s get started!

What is the Volatile Keyword in Java?

It is used to show that a variable can be changed by multiple threads at different times. It ensures that whenever a variable is updated, all other threads immediately see the latest value and no issues occur due to cached copies.

Master Java Programming with Java Training

Boost your coding skills and gain hands-on knowledge in Java.

Explore Now

Why Do We Need the Volatile Keyword in Java?

In a multithreaded Java program, multiple threads may access the same variable at the same time. Without proper control, some threads might read an old value instead of the updated one. The volatile keyword in Java helps prevent this issue by ensuring that all threads always work with the most recent value of a variable. This improves the reliability and consistency of multithreaded applications.

Key reasons for using the volatile keyword:

  • Ensure all threads read the latest value of a shared variable.
  • Prevents threads from using an outdated or cached value.
  • Helps maintain proper communication between multiple threads.
  • Useful when several threads share and update the same variable.
  • Helps keep data consistent in multithreaded Java programs.

Usage of the Volatile Keyword

The volatile keyword is used when a variable is shared between multiple threads and its value may change during program execution. It helps ensure that each thread always reads the most recent value of that variable. Some common usages are:

  • Used for shared variables that are accessed by multiple threads.
  • Helps ensure that changes made by one thread are visible to others.
  • Commonly used for status flags or control variables in multithreaded programs.
  • Declared by placing the keyword volatile before the variable in the code.
  • Helps maintain correct behavior in simple multithreading situations.

Read Also: Java Tutorial for Beginners

Examples of the Volatile Keyword in Java

Following examples show how the volatile keyword is used in Java and how it behaves in a multithreaded environment:

Example 1: Basic Usage

A variable is declared volatile. When one thread updates the value, other threads can immediately see the updated value.

Note: Even if counter is declared volatile, the operation counter++ is not atomic and may lead to race conditions when multiple threads update it simultaneously.

class VolatileExample1 {

    volatile int counter = 0;

    void increment() {
        counter++;
    }

    public static void main(String[] args) {
        VolatileExample1 obj = new VolatileExample1();

        obj.increment();
        System.out.println("Counter value: " + obj.counter);
    }
}

basic usage of volatile keyword in java

How it works:

  • counter is declared as volatile.
  • Any thread reading counter will get the latest value from main memory and not a cached copy.
  • This makes sure about the visibility changes across threads.

Example 2: Volatile with Multiple Threads

Two threads access the same volatile variable. One thread updates it and the other reads the updated value.

class SharedData {
    volatile int value = 0;
}

public class VolatileExample2 {

    public static void main(String[] args) {

        SharedData data = new SharedData();

        Thread writer = new Thread(() -> {
            System.out.println("Writer thread updating value...");
            data.value = 10;
        });

        Thread reader = new Thread(() -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
            }
            System.out.println("Reader thread sees value: " + data.value);
        });

        writer.start();
        reader.start();
    }
}

volatile with multiple threads

How it works:

  • value is shared between threads.
  • The writer thread updates the value.
  • Because it is volatile, the reader thread immediately sees the updated value.

Example 3: Volatile Stop Flag

A worker thread continuously performs a task in a loop. A volatile flag is used to stop the thread from another thread. As the variable is volatile, the worker thread immediately detects the change.

public class VolatileStopExample {

    private volatile boolean stop = false;

    public void runWorker() {

        Thread worker = new Thread(() -> {
            int i = 0;

            while (!stop) {
                System.out.println("Working... " + i++);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("Worker thread stopped.");
        });

        worker.start();
    }

    public void stopWorker() {
        stop = true;
    }

    public static void main(String[] args) throws InterruptedException {

        VolatileStopExample example = new VolatileStopExample();

        example.runWorker();

        Thread.sleep(3000);   // Let the thread run for some time

        System.out.println("Stopping worker thread...");
        example.stopWorker();
    }
}

volatile stop flag

How This Works:

  • stop is declared as volatile.
  • The worker thread keeps running while the stop is false.
  • After 3 seconds the main thread sets stop = true.
  • The variable is volatile, the worker thread immediately reads the updated value and stops.

Example 4: Volatile Status Variable

A volatile variable can also represent the status of a process that multiple threads check.

class DownloadStatus {

    volatile boolean downloadComplete = false;

    public static void main(String[] args) {

        DownloadStatus status = new DownloadStatus();

        Thread downloader = new Thread(() -> {
            System.out.println("Download started...");

            try {
                Thread.sleep(3000);   // Simulate downloading
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            status.downloadComplete = true;
            System.out.println("Download finished.");
        });

        Thread checker = new Thread(() -> {
            while (!status.downloadComplete) {
                System.out.println("Checking download status...");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("Download status detected as complete.");
        });

        downloader.start();
        checker.start();
    }
}

volatile status variable

How It Works:

  • downloadComplete is declared as volatile.
  • The downloader thread simulates a download and then sets the variable to true.
  • The checker thread continuously checks the status.
  • Once the value becomes true, the checker thread detects the change immediately and stops checking.

Volatile vs Synchronized: Key Differences

Both are used in multithreading to manage shared data between threads. Volatile ensures visibility of variable updates across threads and synchronized provides mutual exclusion and thread safe access to critical sections. Here is a differentiation between them:

Parameters Volatile Synchronized
Purpose Ensures visibility of variable changes across threads. Ensures mutual exclusion and synchronization between threads
Locking Does not use locks Uses intrinsic locks.
Thread Safety Provides visibility only, not full thread safety for complex operations. Provides both visibility and atomicity that makes the operations thread safe.
Performance Faster because no locking overhead. Slower compared to volatile due to lock acquisition and release.
Use Case Best for simple flags or status variables shared between threads. Best for critical sections where multiple threads modify shared data.
Atomic Operations Does not guarantee atomicity. Guarantees atomic execution of the synchronized block.
Code Scope Applied to variables only. Applied to methods or blocks of code.

Read Also: Java Interview Questions and Answers

Best Practices for Using the volatile Keyword in Java

1. Use volatile for Visibility, Not for Thread Safety

The volatile keyword guarantees that a variable’s latest value is visible to all threads. When one thread updates a volatile variable, the updated value is immediately visible to other threads. Volatile does not provide full thread safety for complex operations.

2. Use volatile for Simple Shared Flags

volatile works best for variables used as control flags or status indicators that multiple threads read and update. For example:

volatile boolean running = true;

3. Avoid Using volatile for Compound Operations

Operations such as count++, value += 1 or check-then-act logic involve multiple steps. The volatile keyword does not guarantee atomicity for these operations which may lead to race conditions when multiple threads modify the same variable.

4. Do Not Replace Synchronization With volatile

volatile should not be used as a replacement for synchronized. While volatile ensures visibility of variable updates across threads, it does not provide mutual exclusion. If multiple threads modify shared data, synchronization or locking mechanisms are required.

5. Understand that volatile Prevents Instruction Reordering

The Java Memory Model prevents certain read and write operations on volatile variables from being reordered by the compiler or CPU. This helps maintain predictable behavior in multithreaded programs.

6. Be Aware of Performance Impact

Using volatile may introduce a small performance overhead because it prevents some CPU caching and optimization techniques. The overhead is usually minimal, volatile should only be used when visibility guarantees are required.

7. Combine volatile With Synchronization When Necessary

In some cases, volatile may be used together with synchronized blocks or other concurrency mechanisms. This helps achieve both visibility and atomicity when multiple operations must remain consistent across threads.

Start Your Java Certification Journey

Boost your coding skills and gain hands-on knowledge in Java.

Explore Now

Wrapping Up

In this blog, I have explained to you volatile keyword in Java that includes why it is used in multithreaded programs, how it ensures visibility of shared variables and how it is different from synchronized.

After reading this you should start practicing it to get a hands-on practice and confidence for your future projects.

FAQs

1. Why is the volatile keyword important in multithreading?

Volatile makes sure that when one thread changes a variable, other threads immediately see the updated value. It prevents threads from using outdated values stored in their local memory.

2. Does volatile guarantee thread safety in Java?

No, volatile only ensures visibility of changes between threads. It does not make operations atomic. It cannot fully guarantee thread safety when multiple threads modify data.

3. Can volatile be used with methods or only with variables?

Volatile can only be used with variables. It cannot be applied to methods, classes or local variables in Java.

Explore Our Trending Articles-

About the Author
Author Nehal Sharma
About the Author

Nehal Sharma is a skilled content writer with expertise in Java, mobile development, and data analytics. She transforms complex data into actionable insights and has experience in business intelligence, data science, and Salesforce. She also simplifies technical concepts into clear, engaging content for learners and professionals.

Drop Us a Query
Fields marked * are mandatory
×

Your Shopping Cart


Your shopping cart is empty.