Not thread-safe Object publishing

前端 未结 7 2129
眼角桃花
眼角桃花 2020-12-02 21:44

Reading \"Java Concurrency In Practice\", there\'s this part in section 3.5:

public Holder holder;
public void initialize() {
     holder = new Holder(42);
}         


        
7条回答
  •  时光说笑
    2020-12-02 21:53

    I was also very puzzled by that example. I found a website that explains the topic thoroughly and readers might find useful: https://www.securecoding.cert.org/confluence/display/java/TSM03-J.+Do+not+publish+partially+initialized+objects

    Edit: The relevant text from the link says:

    the JMM permits compilers to allocate memory for the new Helper object and to assign a reference to that memory to the helper field before initializing the new Helper object. In other words, the compiler can reorder the write to the helper instance field and the write that initializes the Helper object (that is, this.n = n) so that the former occurs first. This can expose a race window during which other threads can observe a partially initialized Helper object instance.

提交回复
热议问题