How to simulate constructor race conditions?

后端 未结 4 663
故里飘歌
故里飘歌 2020-12-19 23:03

I am reading \"Java Concurrency in practice\" and looking at the example code on page 51.

This states that if a thread has references to a shared object then other t

4条回答
  •  清歌不尽
    2020-12-19 23:26

    Before sleeping, start a new thread which prints the value of n2. You will see the second thread can access the object before the constructor has finished.

    The following example demonstrates this on the Sun JVM.

    /* The following prints
    Incomplete initialisation of A{n=1, n2=0}
    After initialisation A{n=1, n2=2}
     */
    public class A {
        final int n;
        final int n2;
        public A() throws InterruptedException {
            n = 1;
            new Thread(new Runnable() {
                public void run() {
                    System.out.println("Incomplete initialisation of " + A.this);
                }
            }).start();
            Thread.sleep(200);
            this.n2 = 2;
        }
        @Override
        public String toString() {
            return "A{" + "n=" + n + ", n2=" + n2 + '}';
        }
        public static void main(String... args) throws InterruptedException {
            System.out.println("After initialisation " + new A());
        }
    }
    

提交回复
热议问题