Read field stale value after object construction

前端 未结 4 2024
甜味超标
甜味超标 2021-02-05 07:58

I\'m reading a book "Java concurrency in practice" by Brian Goetz. Paragraphs 3.5 and 3.5.1 contains statements that I can not understand.

Consider the followin

4条回答
  •  星月不相逢
    2021-02-05 08:27

    You are probably trying to simulate a concurrency scenario, which I believe is very hard to simulate using a couple of threads.

    The following test-case which you have written is not correct at all is more likely to throw a NullPointerException.

    public class Tests {
    
      private HolderContainer hc = new HolderContainer();
    
      class Initialization implements Runnable {
        public void run() {
          hc.init();
        }
      }
    
      class Checking implements Runnable {
        public void run() {
          hc.holder.assertValue();
        }
      }
    
      public void run() {
        new Thread(new Initialization()).start();  
        new Thread(new Checking()).start(); 
      }
    }
    

    What if your Checking Thread executes before Initialization one?? Also putting a sleep there simply means that executing thread will sleep and does tell you about the internal atomic operations being performed by then.

提交回复
热议问题