Why it is bad practice to create a new thread on constructors?
Findbugs is alerting you to the problem with instruction reordering possibilities around object construction. Although the memory space for a new object is allocated, there is no guarantee that any of the fields have been initialized by the time your InnerThread
has been started. Although the final
fields will be initialized before the constructor finishes, there is no guarantee that if InnerThread
starts to use (for example) aField
when it starts, that it will be initialized. The Java compiler does this for performance reasons. It also has the option to move the initialization of non-final fields to after the new instance has been returned by the constructor.
If you start a new thread in the constructor then there is a chance that the thread will be dealing with a partially initialized object. Even if the thread.start()
is the last statement in your constructor, the new thread may be accessing a partially constructed object because of the reordering. This is part of the Java language specification.
Here's a good link about the topic: calling thread.start() within its own constructor
It mentions the following:
By starting it from within the constructor, you are guaranteed to violate the Java Memory Model guidelines. See Brian Goetz's Safe Construction Techniques for more info.
Edit:
Since you code is starting a new thread that is accessing afield
, according to the Java Memory Model there is no guarantee that afield
will be properly initialized when the thread starts to run.
What I would recommend instead is to add a start()
method on your class that calls the thread.start()
. This is a better practice and makes it more visible to other classes that are using this class that a thread is created in the constructor.