Search code examples
javamultithreadingvolatile

Why the volatile Happens-Before order for Instruction Reordering fails?


I hava following code to test volatile. bEnd and nCount are defined volatile.

nCount = 0, bEnd = false

The Writer thread will set

nCount = 100, bEnd = true

The Reader thread read these viriables and print them. Base on the Java Happens-before order, in my opinion, volatile ensures nCount = 100 when bEnd = true. But sometimes the program print this:

main thread done.
thread Reader running ...
thread Writer running ...
SharedData nCount = 0, bEnd = false
thread Writer bEnd = true
thread Reader nCount = 0, bEnd = true
thread Reader nCount = 100, bEnd = true
thread Reader nCount = 100, bEnd = true
thread Reader done.

How can the Reader get "nCount = 0, bEnd = true" ???

The following code running on windows10, jdk1.8.0_131

public class HappensBeforeWithVolatile {

    public static void main(String[] args) {

        Thread threadWriter = new Thread(new Writer());
        Thread threadReader = new Thread(new Reader());
        threadWriter.start();
        threadReader.start();

        System.out.println("main thread done.");
    }
}

class Writer implements Runnable {

    @Override
    public void run() {
        System.out.println("thread Writer running ...");
        SharedData.nCount = 100;
//        System.out.println("thread Writer nCount = 100");
        SharedData.bEnd = true;
        System.out.println("thread Writer bEnd = true");
    }
}

class Reader implements Runnable {

    @Override
    public void run() {
        System.out.println("thread Reader running ...");
        System.out.println("thread Reader nCount = " + SharedData.nCount + ", bEnd = " + SharedData.bEnd);
        System.out.println("thread Reader nCount = " + SharedData.nCount + ", bEnd = " + SharedData.bEnd);
        if (SharedData.nCount == 0 && SharedData.bEnd) {
            System.out.println("thread Reader CODE REORDER !!!");
        }
        System.out.println("thread Reader nCount = " + SharedData.nCount + ", bEnd = " + SharedData.bEnd);
        System.out.println("thread Reader done.");
    }
}

class SharedData {
    volatile public static boolean bEnd = false;
    volatile public static int nCount = 0;

    static {
        System.out.println("SharedData nCount = " + nCount + ", bEnd = " + bEnd);
    }
}

Solution

  • volatile ensures nCount = 100 when bEnd = true

    Technologically, yes. But the reader did not read them atomically. So it might print nCount = 0 and bEnd = true.

    Here is an example:

    1. Reader reads nCount 0
    2. Wirter writes nCount = 100
    3. Wirter writes bEnd = true
    4. Writer prints thread Writer bEnd = true
    5. Reader reads bEnd true