Suppose I have a simple nio based java server. For example (simplified code):
while (!self.isInterrupted()) {
if (selector.select() <= 0) {
continue;
}
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
SelectableChannel channel = key.channel();
if (key.isValid() && key.isAcceptable()) {
SocketChannel client = ((ServerSocketChannel) channel).accept();
if (client != null) {
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
}
} else if (key.isValid() && key.isReadable()) {
channel.read(buffer);
channel.close();
}
}
}
So, this is a simple single-threaded non-blocking server.
The problem is the following code.
channel.read(buffer);
channel.close();
When I close the channel in the same thread (the thread that accepts the connection and read data), everything works fine. But I had a problem when the connection closed in another thread. for example
((SocketChannel) channel).read(buffer);
executor.execute(new Runnable() {
public void run() {
channel.close();
}
});
In this scenario, I ended the socket in TIME_WAIT state on the server and ESTABLISHED on the client. Thus, the connection does not close gracefully. Any ideas what's wrong? What did I miss?
source
share