0

I'm reading Paul Butcher's "Seven concurrency models in seven weeks", it gives sample code "puzzle.java" in chapter 2.2:

ThreadsLocks/Puzzle/src/main/java/com/paulbutcher/Puzzle.java public class Puzzle { static boolean answerReady = false; static int answer = 0; static Thread t1 = new Thread() { public void run() { answer = 42; answerReady = true; } }; static Thread t2 = new Thread() { public void run() { if (answerReady) System.out.println("The meaning of life is: " + answer); else System.out.println("I don't know the answer"); } }; public static void main(String[] args) throws InterruptedException { t1.start(); t2.start(); t1.join(); t2.join(); } }

So here is a racing condition.

Then it says,

Imagine that we rewrote run() as follows:

public void run() { while (!answerReady) Thread.sleep(100); System.out.println("The meaning of life is: " + answer); }

Our program may never exit because answerReady may never appear to become true.

May I ask why?

athos
  • 6,120
  • 5
  • 51
  • 95

1 Answers1

2

Forgive me if I failed to explain this clearly in the book. I'll try again here :-)

The first thing that you need to recognise is that the loop in t2 will only exit if answerReady becomes true. And the only thing that sets it to true is t1.

So, in other words, for t2 to exit, it needs to see a change in memory made by t1.

The problem is that the JVM makes no guarantees whatsoever about whether changes made by one thread are visible by another thread unless the code is correctly synchronised.

As this code is not correctly synchronised (there are no locks in use whatsoever) the JVM makes no guarantees about whether t2 will ever see the change to answerReady. So the loop may never exit.

Paul Butcher
  • 10,722
  • 3
  • 40
  • 44
  • Although JVM doesn't guarantee but can there be any reason variable will not be written to main memory even after long time (as question says it may not be visible forever) like in this program no other processing is happening? – Vipin Jul 06 '16 at 12:09
  • 1
    Thanks Paul, now I got it. Btw, brilliant book! – athos Jul 06 '16 at 12:59
  • In practice, it almost certainly will eventually be written to memory, @Vipin. But there's no guarantee, so you can't rely on it. – Paul Butcher Jul 06 '16 at 15:11