Java Reference
In-Depth Information
3.2.1. Safe Construction Practices
ThisEscape
illustrates an important special case of escape—when the
this
references
escapes during construction. When the inner
EventListener
instance is published, so is
the enclosing
ThisEscape
instance. But an object is in a predictable, consistent state only
after its constructor returns, so publishing an object from within its constructor can publish
an incompletely constructed object. This is true
evenifthepublicationisthelaststatementin
the constructor.
If the
this
reference escapes during construction, the object is considered
not properly constructed
.
[8]
Do not allow the
this
reference to escape during construction.
A common mistake that can let the
this
reference escape during construction is to start a
thread from a constructor. When an object creates a thread from its constructor, it almost al-
ways shares its
this
reference with the new thread, either explicitly (by passing it to the
constructor) or implicitly (because the
Thread
or
Runnable
is an inner class of the own-
ing object). The new thread might then be able to see the owning object before it is fully
constructed. There's nothing wrong with
creating
a thread in a constructor, but it is best not to
start
the thread immediately. Instead, expose a
start
or
initialize
method that starts
the owned thread. (See
Chapter 7
for more on service lifecycle issues.) Calling an override-
able instance method (one that is neither
private
nor
final
) from the constructor can
also allow the
this
reference to escape.