Not thread-safe Object publishing

前端 未结 7 2130
眼角桃花
眼角桃花 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条回答
  •  旧时难觅i
    2020-12-02 22:15

    Well, in the book it states for the first code block that:

    The problem here is not the Holder class itself, but that the Holder is not properly published. However, Holder can be made immune to improper publication by declaring the n field to be final, which would make Holder immutable; see Section 3.5.2

    And for the second code block:

    Because synchronization was not used to make the Holder visible to other threads, we say the Holder was not properly published. Two things can go wrong with improperly published objects. Other threads could see a stale value for the holder field, and thus see a null reference or other older value even though a value has been placed in holder. But far worse, other threads could see an up-todate value for the holder reference, but stale values for the state of the Holder.[16] To make things even less predictable, a thread may see a stale value the first time it reads a field and then a more up-to-date value the next time, which is why assertSanity can throw AssertionError.

    I think JaredPar has pretty much made this explicit in his comment.

    (Note: Not looking for votes here -- answers allow for more detailed info than comments.)

提交回复
热议问题