Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question about "Java Concurrency in Practice" example

Tags:

I'm looking at a code sample from "Java Concurrency in Practice" by Brian Goetz. He says that it is possible that this code will stay in an infinite loop because "the value of 'ready' might never become visible to the reader thread". I don't understand how this can happen...

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 675
Andy Faibishenko Avatar asked Dec 17 '09 04:12

Andy Faibishenko


People also ask

Is Java Concurrency in Practice still valid?

TL: DR — Yes, Java Concurrency in Practice is still valid and one of the best books to learn Java multithreading and concurrency concepts.

How do you resolve concurrency issues in Java?

The simplest way to avoid problems with concurrency is to share only immutable data between threads. Immutable data is data which cannot be changed. To make a class immutable define the class and all its fields as final. Also ensure that no reference to fields escape during construction.

How does Java support concurrency?

The backbone of Java concurrency is threads (a lightweight process, which has its own files and stacks and can access the shared data from other threads in the same process). The throughput and the interactivity of the program can be improved by performing time-consuming tasks asynchronously or in parallel.

How does Java support concurrency and multithreading?

A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.


1 Answers

Because ready isn't marked as volatile and the value may be cached at the start of the while loop because it isn't changed within the while loop. It's one of the ways the jitter optimizes the code.

So it's possible that the thread starts before ready = true and reads ready = false caches that thread-locally and never reads it again.

Check out the volatile keyword.

like image 140
Rich Schuler Avatar answered Sep 18 '22 13:09

Rich Schuler