Skip to content

Fix race-conditions in selector. #1729

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import java.io.IOException;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.CompletionHandler;
import java.nio.channels.InterruptedByTimeoutException;
import java.nio.channels.SelectionKey;
Expand Down Expand Up @@ -164,19 +165,48 @@ void start() {
}
} finally {
try {
selector.close();
} catch (IOException e) {
// ignore
closePendingSockets();
} finally {
try {
selector.close();
} catch (IOException e) {
// ignore
}
}
}
});
selectorThread.setDaemon(true);
selectorThread.start();
}

private void closePendingSockets() {
for (SocketRegistration pendingRegistration : pendingRegistrations) {
close(pendingRegistration.socketChannel);
}
for (SelectionKey key : selector.keys()) {
close(key.channel());
}
}

private void close(final Channel channel) {
try {
channel.close();
} catch (IOException e) {
LOGGER.debug("Exception closing channel", e);
}
}

void register(final SocketRegistration registration) {
pendingRegistrations.add(registration);
selector.wakeup();

// Selector could become closed while we were trying to register the socket.
// if it becomes closed, then no pending registrations will be cleaned up.
// Therefore, we might end up with a hanging socket channel.
if (!selector.isOpen()) {
pendingRegistrations.remove(registration);
close(registration.socketChannel);
}
}

@Override
Expand Down