Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

JavaWorld Daily Brew

Creating new threads from another thread



Well, I should create a class (called Server), which represents a multi-thread server. This class consists of a constructor, where I can read a specific configuration file to load the port on which the server should listen and other configuration information.
In addition, the Server class contains a list attribute declared as private and some public methods that allow you to change this list.

Any request to modify the list by a client must be handled by a thread. To this end, the server must wait for incoming connections (using a ServerSocket accept), and for each connection request, it must create a new thread.

How can I start the server
, implemented in Server class, without adding additional methods to the class Server itself?

I thought I'd create a primary thread in the constructor of the Server class: I could put the code that creates a new ServerSocket, etc., and that creates others secondary threads inside the run method of this this primary thread. For example (try/catch omitted for simplicity),

public class Server {
    private Vector<Object> list;
   
    public Server() {
        // load configuration file
        ...
        // creates and starts a PrimaryThread
    }
}
public class PrimaryThread implements Runnable {
    ...
    public PrimaryThread(...) {
        ...
    }

    ...
   
    public void run() {
        ServerSocket listening = new ServerSocket(4444);
        ...
        while(true) {
            listening.accept();
            ....
            // creates a new SecondaryThread
        }
    }
}

public class SecondaryThread implements Runnable {
    ...
    public SecondaryThread(...) {
        ...
    }

    ...
   
    public void run() {
        // reply to the client
    }
}

public class MainClass {
    public static void main(...) {
        Server myServer = new Server();
    }
}

The above code should work, but I wonder if it is a good practice: it is a good way to program? Or would it be more correct to add a start and a stop methods to the Server class and remove the PrimaryThread?

Thanks a lot!