Video in progress
How does an NIO Selector work, and how does a single thread serve thousands of connections?
All the SocketChannels are put into non-blocking mode and registered with one Selector. select() asks the OS (epoll on Linux) which channels are ready to read or write, and the thread works only with the ready ones, so it never gets stuck waiting on one slow client.
📖 Answer
The classic model: one connection, one thread, and the thread blocks in read(). 10,000 connections means 10,000 threads, each taking memory for its stack.
The Selector model:
Selector sel = Selector.open();
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress(8080));
server.configureBlocking(false);
server.register(sel, SelectionKey.OP_ACCEPT);
while (true) {
sel.select();
Iterator<SelectionKey> it = sel.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove(); // you must remove it yourself
if (key.isAcceptable()) {
SocketChannel c = server.accept();
c.configureBlocking(false);
c.register(sel, SelectionKey.OP_READ, ByteBuffer.allocate(4096));
} else if (key.isReadable()) {
SocketChannel c = (SocketChannel) key.channel();
ByteBuffer buf = (ByteBuffer) key.attachment();
if (c.read(buf) == -1) { key.cancel(); c.close(); }
}
}
}
The tricky parts:
readcan return only part of a message, so you keep state per connection (the attachment) and find the message boundary yourself;writemay not write everything either; if there is a remainder, you subscribe toOP_WRITEand remove it once the write is done. If you leaveOP_WRITEon all the time, the CPU goes to 100%;- you never do blocking work (a DB query) inside the event loop: it stalls all the connections.
For this reason people rarely write raw Selector code in practice: Netty, Undertow and Reactor Netty have already done it right.
Sign up to mark studied questions and save your progress.