Thread Join Happens Before Visibility

Fields written by a worker thread become visible to the reader only after join returns: the happens-before edge needs no volatile or locks.

JavaData Integrity

Code

snippet
public class JoinHappensBefore {

    // 普通字段:非 volatile、无锁。可见性 (visibility) 由 join 的 happens-before 边保证
    static String payload;
    static int checksum;

    public static void main(String[] args) throws InterruptedException {
        Thread producer = new Thread(() -> {
            payload = "computed by worker";
            checksum = payload.hashCode();
        });
        producer.start();
        producer.join();

        // join 成功返回后,producer 线程的全部写入对 main 可见
        System.out.println("payload  = " + payload);
        System.out.println("checksum = " + checksum);
        System.out.println("finished = " + !producer.isAlive());
    }
}

Thread Join Happens Before Visibility: inside the code

The moving parts are the class JoinHappensBefore.

What to watch for

  • The toolchain by itself suffices; no dependency resolution runs.

Using it

The demo output is labeled (payload =, checksum =, finished =), and each label identifies the operation behind that line.

Key statements

Thread producer = new Thread(() -> {
    payload = "computed by worker";
    checksum = payload.hashCode();
});

Interactive Tools for This Topic

FAQ

What does Thread Join Happens Before Visibility print when run?
Invoke the file as-is — the `payload =`, `checksum =`, `finished =` prefixes identify which step printed each line.