Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

volatile — field visibility between threads

volatile is a reserved keyword marking a field used for communication between threads. It provides visibility and happens-before ordering guarantees, but does not provide mutual exclusion or make operations such as count++ atomic.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

[accessModifier] [static] volatile Type fieldName [= initializer];

volatile is a reserved Java SE 21 keyword and a modifier for an instance field or a static field. It cannot mark local variables, parameters, or methods. Combining final and volatile on the same field is a compile-time error. Square brackets in the syntax shown denote optional parts, not literal Java code.

A write to a volatile field happens-before every subsequent read of that same field, where “subsequent” refers to synchronization order. Through the transitivity of this relationship, earlier writes performed by the writing thread become visible to the reading thread after the corresponding volatile read. This does not promise that another thread will execute immediately.

volatile does not acquire a lock. Although individual reads and writes are atomic, count++ combines a read, a calculation, and a write, so concurrent increments can lose updates. If only one thread writes to count, count++ is still not atomic, but there is no other writer whose write could cause a lost update. For a reference field, volatile applies to the reference, not automatically to the object's fields or array elements. A single volatile reference can nevertheless publish an immutable snapshot that preserves an invariant across several fields. A reader that reads the reference once and takes all the relevant field values from that same snapshot sees a consistent state without additional synchronization.

In the example, value = 42 precedes ready = true. Once the loop reads true, the later read of value must produce 42, even though value is not volatile. The join() call occurs only after printing, so it does not establish this visibility. Busy-waiting consumes processor time; this is a teaching example, not a default production waiting pattern. volatile guarantees neither fair processor scheduling nor a bounded waiting time.

Examples

public class VolatileDemo {
    private static int value;
    private static volatile boolean ready;

    public static void main(String[] args) throws InterruptedException {
        Thread writer = new Thread(() -> {
            value = 42;
            ready = true;
        });
        writer.start();

        while (!ready) {
            // Wait for publication.
        }
        System.out.println(value);
        writer.join();
    }
}

Result

42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources