Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java memory model synchronization: how to induce data visibility bug?

"Java Concurrency in Practice" gives the following example of an unsafe class which due the nature of the java memory model may end up running forever or print 0.

The issue this class is trying to demonstrate is that the variables here are not "shared" between threads. So the value on thread sees can be different from another thread as they are not volatile or synchronized. Also due to the reordering of statements allowed by the JVM ready=true maybe set before number=42.

For me this class always works fine using JVM 1.6. Any idea on how to get this class to perform the incorrect behavior (i.e. print 0 or run forever)?

public class NoVisibility {
    private static boolean ready;
    private static int number;

    private static class ReaderThread extends Thread {
        public void run() {
            while (!ready)
                Thread.yield();
            System.out.println(number);
        }
    }

    public static void main(String[] args) {
        new ReaderThread().start();
        number = 42;
        ready = true;
    }
}
like image 727
DD. Avatar asked Jan 22 '12 13:01

DD.


2 Answers

The problem you have is that you are not waiting long enough for the code to be optimised and the value to be cached.

When a thread on an x86_64 system reads a value for the first time, it gets a thread safe copy. Its only later changes it can fail to see. This may not be the case on other CPUs.

If you try this you can see that each thread is stuck with its local value.

public class RequiresVolatileMain {
    static volatile boolean value;

    public static void main(String... args) {
        new Thread(new MyRunnable(true), "Sets true").start();
        new Thread(new MyRunnable(false), "Sets false").start();
    }

    private static class MyRunnable implements Runnable {
        private final boolean target;

        private MyRunnable(boolean target) {
            this.target = target;
        }

        @Override
        public void run() {
            int count = 0;
            boolean logged = false;
            while (true) {
                if (value != target) {
                    value = target;
                    count = 0;
                    if (!logged)
                        System.out.println(Thread.currentThread().getName() + ": reset value=" + value);
                } else if (++count % 1000000000 == 0) {
                    System.out.println(Thread.currentThread().getName() + ": value=" + value + " target=" + target);
                    logged = true;
                }
            }
        }
    }
}

prints the following showing its fliping the value, but gets stuck.

Sets true: reset value=true
Sets false: reset value=false
...
Sets true: reset value=true
Sets false: reset value=false
Sets true: value=false target=true
Sets false: value=true target=false
....
Sets true: value=false target=true
Sets false: value=true target=false

If I add -XX:+PrintCompilation this switch happens about the time you see

1705    1 % RequiresVolatileMain$MyRunnable::run @ -2 (129 bytes)   made not entrant
1705    2 % RequiresVolatileMain$MyRunnable::run @ 4 (129 bytes)

Which suggests the code has been compiled to native is a way which is not thread safe.

if you make the value volatile you see it flipping the value endlessly (or until I got bored)

EDIT: What this test does is; when it detect the value is not that threads target value, it set the value. ie. thread 0 sets to true and thread 1 sets to false When the two threads are sharing the field properly they see each others changes and the value constantly flips between true and false.

Without volatile this fails and each thread only sees its own value, so they both both changing the value and thread 0 see true and thread 1 sees false for the same field.

like image 142
Peter Lawrey Avatar answered Nov 03 '22 04:11

Peter Lawrey


The java memory model defines what is required to work and what isn't. the "beauty" of unsafe multi-threaded code is that in most situations (especially in contolled dev environments) it usually works. it's only when you get to production with a better computer and load increases and the JIT really kicks in that the bugs start to bite.

like image 31
jtahlborn Avatar answered Nov 03 '22 05:11

jtahlborn