---
title: "Insufficiently Synchronized Java Code"
author: "standalone"
date: "2012-07-09T17:01:46Z"
tags: []
categories: ["编程语言"]
slug: "insufficiently-synchronized-java-code"
draft: false
lastmod: "2013-06-01T17:31:57Z"
id: 1583100
url: "https://standalone.iteye.com/blog/1583100"
---

I'm reading "Java Concurrency in Practice". Section 3.1.1 talks about it may cause surprising results when you do not provide enough synchronization to your shared variables. 

Take a look at the example in the book:


```java

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;    
   }
}

```


Explanations from the book:

NoVisibility could loop forever because the value of ready might never become  visible to the reader thread. Even 
more strangely, NoVisibility could print zero because the write to ready might be made visible to the reader thread 
before the write to number, a phenomenon known as reordering. There is no guarantee that operations in one thread 
will be performed in the order given by the program, as long as the reordering is not detectable from within that thread 
 even if the reordering is apparent to other threads. When the main thread writes first to number and then to done 
without synchronization, the reader thread could see those writes happen in the opposite order or not at all.