Read field stale value after object construction

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

    Did not reproduce it with your code. Here is an example to emulate un-safe publication. The strategy is let one thread publication Holder and let another check its value.

    class Holder {
        private volatile int value;
    
        public Holder(int value, HolderContainer container) {
            container.holder = this;  // publication this object when it is not initilized properly
            try {
                Thread.sleep(10);  
            } catch (Exception e) {
    
            }
            this.value = value; // set value
        }
    
        public int getValue() {
            return value;
        }
    }
    
    class HolderContainer {
    
        public Holder holder;
    
        public Holder getHolder() { 
            if (holder == null) { 
                holder = new Holder(42, this);
            }
            return holder;
        }
    }
    
    
    public class Tests {
    
        public static void main(String[] args) {
            for (int loop = 0; loop < 1000; loop++) {
                HolderContainer holderContainer = new HolderContainer();
                new Thread(() -> holderContainer.getHolder()).start();
                new Thread(() -> {
                    Holder holder = holderContainer.getHolder();
                    int value1 = holder.getValue();  // might get default value
                    try {
                        Thread.sleep(10);
                    } catch (Exception e) {
    
                    }
                    int value2 = holder.getValue(); // might get custom value
                    if (value1 != value2) {
                        System.out.println(value1 + "--->" + value2);
                    }
                }).start();
            }
        }
    
    }
    

提交回复
热议问题