Insufficiently Synchronized Java Code_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Insufficiently Synchronized Java Code

Insufficiently Synchronized Java Code

 2012/7/9 21:25:16  standalone  程序员俱乐部  我要评论(0)
  • 摘要:I'mreading"JavaConcurrencyinPractice".Section3.1.1talksaboutitmaycausesurprisingresultswhenyoudonotprovideenoughsynchronizationtoyoursharedvariables.Takealookattheexampleinthebook:publicclassNoVisibility{privatestaticbooleanready
  • 标签:Java Ron
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:

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.
发表评论
用户名: 匿名