Search code examples
javasocketsshutdownexecutorservice

How to shut down a waiting server?


I created a little (single thread) server and put the "work"-code in a Runnable. This runnable is then executed in a background-thread using Javas Executor Framework:

ExecutorService exec = Executors.newSingleThreadExecutor();
exec.execute(runnable);

So now, I'm searching for a good way to shut this server down. I want to add the possibility to restart the Server without restarting the program, so terminating the whole process is not an option.

What I have found is something like this:

class LifecycleWebServer {
    private final ExecutorService exec = ...;

    public void start() throws IOException {
        ServerSocket socket = new ServerSocket(80);
        while (!exec.isShutdown()) {
            final Socket conn = socket.accept();
            // Do stuff with the connection...
        }
    }

    public void stop() { exec.shutdown(); }
}

The thing that bothers me is, that if the program has reached line 7 (socket.accept()), and I call the stop()-method, the Server will still wait until one last connection was made and then shutdown.

Is there any preferred way to deal with this?


Solution

  • So, it seams that calling close() on the waiting ServerSocket is one way to do this. In that case, the accept()-method will throw a SocketException, which you'll need to catch.

    Another, maybe clearer way is to use a "Poison Pill", which is explained in detail here: How to interrupt a BlockingQueue which is blocking on take()?