Read field stale value after object construction

前端 未结 4 1957
甜味超标
甜味超标 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:35

    I tried to test the problem with the following code.

    Test:

    public class Test {
        public static boolean flag =true;
        public static HolderContainer hc=new HolderContainer();
    
        public static void main (String args[]){    
            new Thread(new Initialization()).start();
            new Thread(new Checking()).start();
        }
    }
    
    class Initialization implements Runnable {
        public void run() {
            while (Test.flag){
                Test.hc=new HolderContainer();
                Test.hc.init();
                }
        }
    }
    
    class Checking implements Runnable {
        public void run() {
            try{
                Test.hc.holder.assertValue();
            }
            catch (NullPointerException e) {
            }    
        }
    }
    

    Holder:

    public class Holder {
        private int value;
            public Holder(int value) { 
            this.value = value;
        }
    
        public void assertValue() {
            if (value != value) {
                System.out.println("Magic");
                Test.flag=false;
            }
        }
    }
    
    class HolderContainer {
        public Holder holder;
        public void init() {
            holder = new Holder(42);  
        }
    }
    

    I never got the program to evaluate value!=value to true. I don't think this proves anything and didn't run it for more than a couple minutes, but I hope this will be a better starting point for a well designed test or at least help to figure out some possible flaws in the tests.

    I tried to insert a sleep between Test.hc=new HolderContainer(); and Test.hc.init();, between public Holder holder; and public void init() { and after public void init() {.

    I am also concerned that checking if a value is null or catching the NullPoiterException may affect the timing too much.

    Please note that the currently accepted answer to Improper publication of Java Object Reference says this problem is probably impossible under an x86 architecture. It may also be JVM dependent.

提交回复
热议问题