What is an "incompletely constructed object"?
Posted
by Joonas Pulakka
on Stack Overflow
See other posts from Stack Overflow
or by Joonas Pulakka
Published on 2010-03-25T06:58:20Z
Indexed on
2010/03/25
7:03 UTC
Read the original article
Hit count: 505
Goetz's Java Concurrency in Practice, page 41, mentions how this
reference can escape during construction. A "don't do this" example:
public class ThisEscape {
public ThisEscape(EventSource source) {
source.registerListener(
new EventListener() {
public void onEvent(Event e) {
doSomething(e);
}
});
}
}
Here this
is "escaping" via the fact that doSomething(e)
refers to the enclosing ThisEscape
instance. The book states:
Publishing an object from within its constructor can publish an incompletely constructed object. This is true even if the publication is the last statement in the constructor. If the
this
reference escapes during construction, the object is considered not properly constructed.
I don't quite get this. If the publication is the last statement in the constructor, hasn't all the constructing work been done before that? How come is this
not valid by then? Apparently there's some voodoo going on after that, but what?
© Stack Overflow or respective owner