Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling new thread inside is constructor

Is it correct to create a thread and call its start() method inside a class' constructor as done here?

public class Server implements Runnable {

    private ServerSocket server;

    public Server(int port) {
        try {
            //Opens a new server 
            server = new ServerSocket(port);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        new Thread(this, "Server").start();
    }

    @Override
    public void run() {
    }
}
like image 566
Mazzy Avatar asked Jan 13 '12 18:01

Mazzy


People also ask

Can we call Thread inside Thread?

Yes a thread can launch another thread, and that thread can launch thread(s) and on and on... In the run() method of a thread - you can create and start other threads.

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.

Can we call method inside constructor?

Yes, as mentioned we can call all the members of a class (methods, variables, and constructors) from instance methods or, constructors.

Which is the correct constructor for Thread?

Which of the following is a correct constructor for thread? Explanation: Thread(Runnable a, String str) is a valid constructor for thread.


2 Answers

IMHO, do not do this. You're allowing the this reference to escape during construction.

like image 71
mre Avatar answered Nov 14 '22 21:11

mre


Granted, your code isnt doing it but what if your code looked like this:

public Server(int port)
{       
    new Thread(this, "Server").start();

    try
    {
        //Opens a new server 
        server = new ServerSocket(port);
    }
    catch (IOException ioe){ ioe.printStackTrace(); }

}
@Override    
public void run(){
    if(server == null)throw new NullPointerException();// this may happen
}
}

The server reference may be null even though no exception occurs. This is because the Thread will use the created runnable and invoke the run method even if the constructor of your class hasn't finished.

like image 33
John Vint Avatar answered Nov 14 '22 23:11

John Vint