Keeping a HttpServer alive

188 Views Asked by At

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?

1

There are 1 best solutions below

3
On

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.