Java Concurrency Interview

Patterns and antipatterns question 155 of 180 senior

Why should you not start a thread from a constructor?

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.

antipatterns publication

Quiz yourself on Patterns and antipatterns Suggest a correction