Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not to start a thread in the constructor? How to terminate?

I am learning how to use threads in Java. And I wrote a class that implements Runnable to run concurrently to another thread. The main thread handles listening to the serial port where as the second thread will handle sending data to that same port.

public class MyNewThread implements Runnable {     Thread t;      MyNewThread() {         t = new Thread (this, "Data Thread");         t.start();     }      public void run()  {         // New Thread code here      } 

There first thread starts the second like this:

public class Main {     public static void main(String[] args) throws Exception{         new MyNewThread();         // First thread code there     }   } 

This works but my complier flags a warning saying: It is dangerous to start a new thread in the constructor. Why is this?

The second part to this question is: how if I have a loop running in one thread (the serial port listen thread) and I type an exit command in my second thread. How do I get the first thread to terminate? Thanks.

like image 540
Zac Avatar asked Apr 11 '11 15:04

Zac


People also ask

Why we should not stop a thread by calling its stop () method?

Previously, methods suspend(), resume() and stop() were used to manage the execution of threads. But these methods were deprecated by Java 2 because they could result in system failures. Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method.

Can we start a thread in constructor?

Avoid starting threads in constructors. Typically, the constructor of a class only constructs the thread object, and a separate start method should be provided to start the thread object created by the constructor.

Can we start a terminated thread in Java?

Java threads cannot be restarted. From the javadoc: It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.


2 Answers

To your first question: Starting a thread in a constructor passing in this escapes this. That means that you are actually giving out a reference to your object before it is fully constructed. The thread will start before your constructor finishes. This can result in all kinds of weird behaviors.

To your second question: There is no acceptable way to force another thread to stop in Java, so you would use a variable which the thread would check to know whether or not it should stop. The other thread would set it to indicate that the first thread would stop. The variable has to be volatile or all accesses synchronized to ensure proper publication. Here is some code which would be something like what you want.

public class MyNewThread implements Runnable {      private final Thread t;     private volatile boolean shouldStop = false;      MyNewThread() {         t = new Thread (this, "Data Thread");     }      public void start() {         t.start();     }      public void stop() {             shouldStop = true;     }      public void run()  {          while(!shouldStop)          {              // do stuff          }     } } 

Whatever wants to create and start the thread would do:

MyNewThread thread = new MyNewThread(); thread.start(); 

Whatever wants to stop the thread would do:

thread.stop(); 
like image 154
Justin Waugh Avatar answered Oct 04 '22 10:10

Justin Waugh


Lets take a look at a basic example:

class MyClass implements Runnable{    int a = 0;    String b = null;     public MyClass(){        new Thread(this).start();        b = "Foo";    }     public void run(){       a = b.length(); //can throw NullPointerException    } } 

In this instance the MyClass.this is said to escape the constructor. That means that the object is available to reference but all of its fields that are being built in the constructor may not be created. To take this to another level what if b was final You would expect it to be available but it is not ensured. This is known as a partially constructed objects and is perfectly legal in java.

like image 26
John Vint Avatar answered Oct 04 '22 12:10

John Vint