Language syntax

Volatile publication

A volatile write and subsequent read of the same field provide an ordering edge; not compound atomicity.

Formal Syntax & Structure

java syntaxjava
volatile Snapshot current;

Working Example

Example Snippetjava
import java.time.Duration;import java.util.concurrent.*;public class Main {    // Only finite tasks and timed coordination are used in these examples.    static void finish(Thread thread) throws InterruptedException {        try {            if (!thread.join(Duration.ofSeconds(3))) {                thread.interrupt();                if (!thread.join(Duration.ofSeconds(3))) throw new AssertionError("worker did not stop");                throw new AssertionError("worker timed out");            }        } catch (InterruptedException e) {            thread.interrupt();            throw e;        }    }    static void meet(CyclicBarrier barrier) {        try { barrier.await(3, TimeUnit.SECONDS); }        catch (InterruptedException e) {            Thread.currentThread().interrupt();            throw new AssertionError("unexpected cancellation", e);        } catch (BrokenBarrierException | TimeoutException e) { throw new AssertionError(e); }    }    record Snapshot(String sku, int stock) {}    static class Holder { volatile Snapshot current; }    public static void main(String[] args) throws Exception {        Holder holder = new Holder();        CyclicBarrier start = new CyclicBarrier(2);        Thread writer = new Thread(() -> { meet(start); holder.current = new Snapshot("PEN", 42); });        Thread reader = new Thread(() -> {            meet(start);            Snapshot observed = holder.current;            if (observed != null && (!observed.sku().equals("PEN") || observed.stock() != 42))                throw new AssertionError("invalid snapshot");            System.out.println("allowed observation");        });        writer.start(); reader.start();        try { finish(writer); } finally { finish(reader); }        System.out.println(holder.current.stock());    }}
Java Reference