Handle rare race conditions

This commit is contained in:
2021-06-02 15:03:30 +02:00
parent 240f50d526
commit 46515dbade
2 changed files with 15 additions and 2 deletions
src/org/omegazero/net

@ -167,7 +167,15 @@ public abstract class SelectorHandler {
Iterator<SelectionKey> iterator = this.selector.selectedKeys().iterator();
while(iterator.hasNext()){
SelectionKey key = iterator.next();
this.handleSelectedKey(key);
// CancelledKeyException is likely caused by an extremely rare race condition when one thread is executing this handleSelectedKey handler
// while another thread called close() on the channel. The handler likely attempts to interact with the now canceled key and causes this exception
try{
this.handleSelectedKey(key);
}catch(java.nio.channels.CancelledKeyException e){
SelectableChannel channel = key.channel();
logger.warn("Caught CancelledKeyException on channel ", channel);
channel.close();
}
iterator.remove();
}
}

@ -167,6 +167,10 @@ public abstract class TCPServer extends InetConnectionSelector implements InetSe
if(key.isAcceptable()){
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = serverChannel.accept();
if(socketChannel == null){
logger.warn("Received OP_ACCEPT but no socket is available");
return;
}
InetConnection conn = this.handleConnection(socketChannel);
conn.setOnLocalClose(super::onConnectionClosed);
@ -189,7 +193,8 @@ public abstract class TCPServer extends InetConnectionSelector implements InetSe
conn.handleData(data);
});
}
}
}else
throw new RuntimeException("Invalid key state");
}