1

I want to demonstrate to my self the visibility thread-safety problem when accessing to a variable from more than one thread without using any kind of synchronisation.

I'm running this example from Java Concurrency in Practice:

public class NoVisibility {

    private static boolean ready;
    private static int number;

    private static class ReaderThread extends Thread {

        @Override
        public void run() {
            while (!ready) {
                Thread.yield();
            }
            System.out.println(number);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new ReaderThread().start();
        number = 42;
        ready = true;
    }
}

How to make it loop forever instead of printing 42 every time I run (looping for ever means that the modification of the variable ready = true; in the ReaderThread thread is not visisble to the main thread).

Salah Eddine Taouririt
  • 24,925
  • 20
  • 60
  • 96
  • Is this really running 42 times? – kosa Aug 27 '13 at 18:27
  • check this question: http://stackoverflow.com/questions/2787094/how-to-demonstrate-java-multithreading-visibility-problems – Katona Aug 27 '13 at 18:33
  • 2
    possible duplicate of [question about "Java Concurrency in Practice" example](http://stackoverflow.com/questions/1919469/question-about-java-concurrency-in-practice-example) – Eric Stein Aug 27 '13 at 18:50

1 Answers1

1
public static void main(String[] args) throws InterruptedException {
    new ReaderThread().start();
    number = 42;
    //put this over here and program will exit
    Thread.sleep(20000);
    ready = true;
}

Place the Thread.sleep() call for 20 secs what will happen is JIT will kick in during those 20 secs and it will optimize the check and cache the value or remove the condition altogether. And so the code will fail on visibility.

To stop that from happening you MUST use volatile.

Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120