java this quote escape

Code! ! ! ! ! ! ! ! ! !

public class FinalReferenceEscapeExample {
    final int i;
    static FinalReferenceEscapeExample obj;

    public FinalReferenceEscapeExample () {
        i = 1;                              //1写final域
        obj = this;                          //2 this引用在此“逸出”
    }

    public static void writer() {
        new FinalReferenceEscapeExample ();
    }

    public static void reader {
        if (obj != null) {                     //3
            int temp = obj.i;                 //4
        }
    }
}

Suppose there are two threads, one thread A executes the writer() method, and the other thread B executes the reader() method.

Operation 2 here makes the object visible to thread B before it is constructed. Even if operation 2 here is the last step of the constructor, and operation 2 is behind operation 1 in the program, the thread that executes the read() method may still not be able to see the initialized value of the final field, because before the constructor returns , The reference of the constructed object cannot be visible to other threads, the final field may not be initialized yet

Guess you like

Origin blog.csdn.net/qq_42407917/article/details/111149687