ServerSocket timeout and queued connections

I have a ServerSocket which accepts connections in an indefinite loop. However, I would like it to stop accepting connections and finish the processing for the connections currently open when the user asks to shut the program down.

I have a shutdown hook which sets a flag so that the program knows of the user’s intentions for it not to accept any more connections. However, by the time this flag is set, it’s already blocked on accept(). If I do something like this:

ServerSocket servsoc = new ServerSocket(port);
servsoc.setSoTimeout(2000);

// Infinite loop processing connections
while (!shutdown) {
    do {
        try {
            connected = true;
            socket = servsoc.accept();
        } catch (SocketTimeoutException tim) {
            connected = false;
        }
    } while (!shutdown && !connected)

    if (connected) {
        ... remainder of code ...
    }
}

Could the ServerSocket ever drop connections which are queued on it?

That’s another question; are connections queued?

You have loop in the loop. Your code can handle only one connection.
You can try every incoming socket process in new thread and somehow hold global state (your shutdown hook), maybe in some singleton?

From some connection thread you can set global variable and stop accept new sockets.

Could the ServerSocket ever drop connections which are queued on it?

Not with this code. If the timeout occurs there aren’t any queued connections to lose.

That’s another question; are connections queued?

Yes, there is a thing called the ‘backlog queue’, whose size can be controlled vaguely by the backlog parameter of the constructor.