Constructor synchronization in Java

前端 未结 6 1112
执笔经年
执笔经年 2020-11-28 09:17

Someone somewhere told me that Java constructors are synchronized so that it can\'t be accessed concurrently during construction, and I was wondering: if I have a constructo

6条回答
  •  天涯浪人
    2020-11-28 09:49

    You've been misinformed. What you describe is actually referred to as improper publication and discussed at length in the Java Concurrency In Practice book.

    So yes, it will be possible for another thread to obtain a reference to your object and begin trying to use it before it is finished initializing. But wait, it gets worse consider this answer: https://stackoverflow.com/a/2624784/122207 ... basically there can be a reordering of reference assignment and constructor completion. In the example referenced, one thread can assign h = new Holder(i) and another thread call h.assertSanity() on the new instance with timing just right to get two different values for the n member that is assigned in Holder's constructor.

提交回复
热议问题