0

I am writing my first Java web server, using com.sun.net.httpserver. I am wondering if this bit of code is logical or necessary. Specifically, I am wondering if the server will stop at some point, and need to be manually restarted.

/**
 * Starts server, on error sleeps for 500ms and restarts server
 */
private static void runServer(HttpServer server) {
    try {
        server.start();
    } catch (Exception e) {
        e.printStackTrace();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        runServer(server);
    }
}

Does this make sense? Or should I just call server.start() and assume it won't timeout or stop?

Avalanche
  • 386
  • 2
  • 10

1 Answers1

1

Just call server.start().

Your code seems to be trying to restart the server recursively, but it won't, due to a confusion about method names, and in any case it won't catch exceptions in the server, which runs in a background thread.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Thanks for the help. So the catch statement won't work around server.start()? What happens when/if the server throws an exception? – Avalanche May 26 '14 at 03:26
  • Ack I just saw the typo in the method names, fixed that. – Avalanche May 26 '14 at 03:46
  • What happens if the server throws an exception isn't specified, but it would mostly be your own `HttpHandler` that did that, and it's if you throw an `IOException` from that it will certainly terminate the associated conversation and possibly the thread that's handling the connection. If the `HttpServer` itself throws an exception during construction it's something like a bind error where it couldn't even get started. – user207421 May 26 '14 at 04:34