Question

So here's the code that should be the source of my error:

try {
config = new Configuration(configFile);
} catch (ConfigurationException e1) {}

try {
    // Create a ServerSocket 
    ss = new ServerSocket(PORT);
    System.out.println("Server bound at port " + ss.getLocalPort());
}catch (Exception e) {}

new ServerThread(ss, config).start();

This is the first time I'm creating a thread so the thread can't already be running. I'm also not referencing this thread again once it has been created so I'm not sure how I could be getting an IllegalThreadStateException.

Here's the stack trace:

Exception in thread "Thread-3" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at HttpServer.<init>(HttpServer.java:36)

Any help would be GREATLY appreciated.

EDIT: Changed the thread starting code to this:

ServerThread initServerThread = new ServerThread(ss, config);
System.out.println(initServerThread.getState().toString());
initServerThread.start();

The thread state is "RUNNABLE"

Also here's the thread class...

public class ServerThread extends Thread {

ServerSocket serverSocket;
Socket nextClient;
Configuration config;

public ServerThread(ServerSocket ss, Configuration newConfig) {
    super();
    serverSocket = ss;
    config = newConfig;
    start();
}

public void run() {
    try {
        nextClient = serverSocket.accept();
    } catch (IOException e) {
        System.err.println(e);
        System.err.println("Usage: java HttpRequest <port>");
    }

    // Create new thread to listen for next incoming connection.
    new ServerThread(serverSocket, config).start();

    try {
        nextClient = serverSocket.accept();
    } catch (IOException e) {}

    HttpRequestHandler httpHandler = new HttpRequestHandler(nextClient, config);
    httpHandler.parseHttpRequest();
    }
}
Was it helpful?

Solution

The constructor also starts the thread:

public ServerThread(ServerSocket ss, Configuration newConfig) {
    super();
    serverSocket = ss;
    config = newConfig;
    start();
}

By the time the ServerThread constructor returns, the thread has already been started, so you must not call start() outside the constructor.

Or, perhaps better, you could remove the start() call from the constructor, and limit it to its primary job of creating the ServerThread object.

OTHER TIPS

"This is the first time I'm creating a thread so the thread can't already be running. "

I think you're wrong. Use a debugger, or show us your thread class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top