Course contentsShow
← Java
Lesson 2681 of 2,87049. Synchronization and LockingFree lesson

The volatile Keyword: Basic Syntax and Semantics

Understand how to declare volatile fields and what guarantees the JVM provides for volatile variable access.

The volatile Keyword: Basic Syntax and Semantics

What you'll learn: How to declare volatile fields and the exact guarantees the JVM provides for volatile variable access.

Understanding volatile Syntax

The volatile keyword is a field modifier that tells the JVM to handle a variable specially. Here's the basic syntax:

public class SharedData {
    private volatile boolean flag = false;
    private volatile int counter = 0;
    private volatile String message;
}

Simply place volatile before the type when declaring a field. That's it—no special methods or setup required.

What volatile Guarantees

When you declare a field as volatile, the JVM provides two critical guarantees:

1. Visibility Guarantee: Every read of a volatile variable sees the most recent write by any thread. No thread-local caching or optimization can hide updates. Think of it as forcing all threads to read from and write to a shared whiteboard, rather than keeping private copies.

2. Ordering Guarantee: Writes to volatile variables happen-before subsequent reads. This prevents certain compiler and CPU reorderings that could make your code behave unexpectedly.

private volatile boolean ready = false;
private int data = 0;

// Thread 1
data = 42;
ready = true;  // volatile write

// Thread 2
if (ready) {  // volatile read
    // Guaranteed to see data = 42
    System.out.println(data);
}

What volatile Does NOT Guarantee

Important: volatile ensures visibility, but not atomicity. Operations like counter++ are still not thread-safe, even on a volatile variable, because they involve read-modify-write cycles.

Key Takeaway: The volatile keyword declares a field whose reads always see the latest write from any thread, providing visibility and ordering guarantees but not atomic compound operations.