3

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?

Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111
  • I posted a similar question for socket code written in C/C++ and got a great answer. I suspect you need to use non-blocking sockets to achieve a similar effect. Have you tried just closing the socket from the other thread and catching an exception thrown by socket.accept? I'm actually not sure if that will work. http://stackoverflow.com/questions/2486335/wake-up-thread-blocked-on-accept-call – selbie Dec 27 '11 at 23:48
  • 2
    similar question: http://stackoverflow.com/questions/2983835/how-can-i-interrupt-a-serversocket-accept-method - seems like you need to close the socket. – Ray Tayek Dec 28 '11 at 00:11
  • [similar question][1]: - seems like you need to close the socket [1]: http://stackoverflow.com/questions/2983835/how-can-i-interrupt-a-serversocket-accept-method – Ray Tayek Dec 28 '11 at 01:55
  • Could NIO be used to make the socket interruptible? This certainly works for client sockets; I've never tried server sockets. – hertzsprung Feb 21 '13 at 14:10

1 Answers1

1

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()?

Community
  • 1
  • 1
Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111