Video in progress

Strong Middle 📁 IO and NIO

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:

  • read can return only part of a message, so you keep state per connection (the attachment) and find the message boundary yourself;
  • write may not write everything either; if there is a remainder, you subscribe to OP_WRITE and remove it once the write is done. If you leave OP_WRITE on 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.