Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: starting a new thread in a constructor

Why is starting a new thread in a constructor frowned upon in Java (or anywhere, for that matter). I'm getting warnings from Netbeans for doing so, but it isn't giving me any refactoring suggestions. I'm writing a client/server Swing application, and the thread I'm starting is in the server's JFrame constructor, in order to continuously listen for client datagrams.

Why is this not good practice and how should I avoid it?

like image 389
Richard Stokes Avatar asked Nov 08 '11 21:11

Richard Stokes


People also ask

Can you start a thread in a constructor Java?

There's nothing inherently wrong with creating a Thread inside a constructor. However, it's highly discouraged to start it immediately, as most of the time, we end up with an escaped this reference, either explicitly or implicitly.

How do you initialize a thread?

There are mainly Three ways to create a new thread: (1) By implementing Runnable interface in your class. (2) By extending Thread class. (3) By using inner class.


2 Answers

Starting a thread from the constructor lets the started thread access the object being constructed before it's properly constructed, and thus makes a not completely constructed object available to the new thread.

You could create the thread in the constructor, and provide a "startup" method to start the thread from the outside.

Or you could make the constructor and startup methods private and provide a static factory method which would create the object, start the thread, and return the created object.

like image 67
JB Nizet Avatar answered Sep 23 '22 00:09

JB Nizet


Have a look at this link http://www.ibm.com/developerworks/java/library/j-jtp0618/index.html#code4

This is do with implicit references to this and subclassing.

like image 40
Ravi Bhatt Avatar answered Sep 24 '22 00:09

Ravi Bhatt