Patterns and antipatterns question 155 of 180 senior
Why should you not start a thread from a constructor?
- It is slower than starting it later
- Correct: Because
thisescapes before construction finishes, so the new thread can observe uninitialised fields, including in a subclass whose constructor has not run yet - Because constructors cannot throw
InterruptedException - Because the thread would be a daemon
new Thread(this).start() inside a constructor publishes this before the object is finished. The
new thread may see default values in fields the constructor is about to set, and the final-field
guarantee does not apply because the reference escaped before the freeze.
Subclassing makes it worse: the superclass constructor runs first, so the thread starts while every subclass field is still zero, and the object it sees may never have existed in a valid state.
The same argument applies to registering a listener, publishing to a static registry or passing this
to anything from a constructor. The fix is a factory method or a separate start() call, so
construction completes before the object is shared. This is the escape half of safe publication.
Quiz yourself on Patterns and antipatterns Suggest a correction