Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

volatile

Marks a field whose changes are immediately visible to all threads.

Available since: Java 1.0

Syntax

private volatile boolean running = true;

Examples

A flag that stops a worker thread:

class Worker implements Runnable {
    private volatile boolean running = true;
 
    public void run() {
        long ticks = 0;
        while (running) {
            ticks++;
        }
        IO.println("worker stopped");
    }
 
    void stop() {
        running = false;
    }
}
 
void main() throws InterruptedException {
    var worker = new Worker();
    Thread t = new Thread(worker);
    t.start();
    Thread.sleep(100);
    worker.stop();
    t.join();
    IO.println("main finished");
}

Output:

worker stopped
main finished

Notes

Without volatile the thread may never see the new value of running and spin forever. volatile guarantees visibility but not atomicity: count++ on a volatile field still loses updates — use AtomicInteger or synchronized for that.

See also

  • synchronized — Lets only one thread at a time run a block of code.
  • AtomicInteger — An integer that can be changed safely from several threads without locks.

In the tutorial

  • Synchronization — Race conditions in Java and how to avoid them — synchronized methods and blocks, atomic classes like AtomicInteger, ReentrantLock and a shared lock object.

Thanks for reading!

Donate to the site — we work hard for you.