What is an “incompletely constructed object”?

前端 未结 3 1380
太阳男子
太阳男子 2020-11-28 12:14

Goetz\'s Java Concurrency in Practice, page 41, mentions how this reference can escape during construction. A \"don\'t do this\" example:

public         


        
相关标签:
3条回答
  • 2020-11-28 12:39

    There is a small but finite time between the registerListener ending and the constructor returning. Another thread could use come in at that time and attempt to call doSomething(). If the runtime didn't return straight to your code at that time, the object could be in a invalid state.

    I'm not sure of java really but one example I can think of is where possibly the runtime relocates the instance before returning to you.

    Its a small chance I grant you.

    0 讨论(0)
  • 2020-11-28 12:42

    Another problem arises when you subclass ThisEscape, and the child class invokes this consructor. The implicit this reference in the EventListener would have an incompletely constructed object.

    0 讨论(0)
  • 2020-11-28 12:43

    The end of a constructor is a special place in terms of concurrency, with respect to final fields. From section 17.5 of the Java Language Specification:

    An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.

    The usage model for final fields is a simple one. Set the final fields for an object in that object's constructor. Do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields. It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are.

    In other words, your listener could end up seeing final fields with their default values if it examines the object in another thread. This wouldn't happen if listener registration happened after the constructor has completed.

    In terms of what's going on, I suspect there's an implicit memory barrier at the very end of a constructor, making sure that all threads "see" the new data; without that memory barrier having been applied, there could be problems.

    0 讨论(0)
提交回复
热议问题