`
standalone
  • 浏览: 612985 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Insufficiently Synchronized Java Code

    博客分类:
  • java
阅读更多
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.
分享到:
评论

相关推荐

    ZMP 实现机器人行走

    ZMP 实现机器人行走 This paper is devoted to the permanence of... Finally, some unresolved or insufficiently treated phenomena that may yield a significant improvement in robot performance are considered.

    SetupEMPB85xx.exe

    The device is designed to speed-up system start-up time when the main energy storage element (aka Long Term Storage – LTS) is completely discharged or insufficiently charged to supply the application...

    中文情感分析词典数据集(基于词典).zip

    6. insufficiently-2.txt:可能表示不足或不满意的词汇,例如“不够”、“不足”。 7. positive-emotion.txt:正向情感词汇,如“高兴”、“满足”。 8. over-1.txt:可能表示过度或过量的情感表达,如“过分”、...

    Hostility and learning in an introductory psychology course

    Hostility and learning in an introductory psychology course HOSTILITY AND LEARNING I N AN INTRODUCTORY PSYCHOLOGY COURSE ...results have been contradictory or insufficiently controlled. For e

    心理学入门课程中的敌意和学习

    Hostility and learning in an introductory psychology course HOSTILITY AND LEARNING I N AN INTRODUCTORY PSYCHOLOGY COURSE ...results have been contradictory or insufficiently controlled. For e

Global site tag (gtag.js) - Google Analytics