Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading shared variable from another thread (Effective Java #66)

In Effective Java: item 66, Joshua Bloch gave an example about life failure:

// Broken! - How long would you expect this program to run
class StopThread {
    private static boolean stopRequested = false;

    public static void main(String[] args) 
            throws InterruptedException {

        Thread backgroundThread = new Thread(new Runnable() {
            public void run() {
                int i = 0;
                while (!stopRequested) {
                    i++;
                }
           }
        });
        backgroundThread.start();

        TimeUnit.SECONDS.sleep(1);
        stopRequested = true;
    }   
}

As Joshua Bloch said, this program would not terminate. But, if I change i++ into System.out.println(i++), it terminates successfully!

I can't figure out how it happens!

like image 616
HuangDong.Li Avatar asked Feb 22 '16 16:02

HuangDong.Li


2 Answers

The problem is related to the memory value of the variable stopRequest.

This variable is not defined as volatile.

If you have a two processors the inner thread check the value of stopRequest taken from its registry.

The main thread alter the value of stopRequest in the registry of the other processor.

So the main thread modify a value of stopRequest but the thread see only a copy of it that never changes.

Modified after take a look at the source code of PrintStream (thanks to the commend of ΔλЛ): Using a System.out.print command will use an explicit synchronized block to print the value passed to it this will grant that the value of stopRequest is taken from the main memory and not from the registry of the processor.

Adding a volatile keyword will inform the JVM to take the value from the main memory instead from the registries of the processors and it solve the problem.

Also using the keyword synchronized will solve this problem because any variable used in the synchronized block is taken and update the main memory.

Memory model without volatile (Main thread use Processor 1 and explicit thread use Processor 2)

Processor 1         Processor 2     Main memory
-----------         -----------     -----------
  false                false           false
  true                 false           true       // After setting 
                                                  //stopRequest to true

Defining stopRequest as volatile where all threads read stopRequest from main memory.

    Processor 1         Processor 2     Main memory
-----------         -----------     -----------
       NA                   NA           false
       NA                   NA           true       // After setting 
                                                  //stopRequest to true
like image 58
Davide Lorenzo MARINO Avatar answered Oct 04 '22 00:10

Davide Lorenzo MARINO


Since you are not telling the thread that stopRequested is a value that can be modified from outside that thread there are no guarantees that the while will evaluate to the most recent value of the variable.

This is why the volatile keyword is useful in this situation, because it will explicitly enforce that stopRequested value, when read, will be the most recent value set by any thread.

There are further considerations, actually from the point of view of the thread, stopRequested is a loop invariant, since it is never set by only read, so optimization choices should be considered too: if a value is thought not to be modified then there is no reason to evaluate it on each iteration.

like image 45
Jack Avatar answered Oct 03 '22 22:10

Jack