Object creation (state initialisation) and thread safety

后端 未结 4 1037
你的背包
你的背包 2021-01-24 17:18

I am look into the book \"Java Concurrency in Practice\" and found really hard to believe below quoted statement (But unfortunately it make sense).

http://www.informit.c

4条回答
  •  佛祖请我去吃肉
    2021-01-24 17:47

    I guess theoretically it is possible. It is similar to double checked locking problem.

    public class Test {
        static Holder holder;
    
        static void test() {
            if (holder == null) {
                holder = new Holder(1);
            }
            holder.assertSanity();
        }
    ...
    

    If test() is called by 2 threads, thread-2 might see the holder in a state when initialization is still in progress so n != n may happen to be true. Here is bytecode for n != n:

    ALOAD 0
    GETFIELD x/Holder.n : I
    ALOAD 0
    GETFIELD x/Holder.n : I
    IF_ICMPEQ L1
    

    as you can see JVM loads field n to operand stack twice. So it may happen that the first var gets value before init and the seccond after init

提交回复
热议问题