Scrivio Interview library
InternalsIntermediate8 min read · updated 12 November 2026

How does a Selector enable one thread to serve many connections? Describe the main loop and the role of SelectionKey interest sets.

A Selector lets one thread watch many non-blocking channels at once. Each channel is registered with the selector together with an interest set, the events we care about (accept, read, write), and selector.select() blocks until the operating system reports that at least one of them is ready. The thread then handles only the ready keys, removes each from the selected set, and goes back to select().

Why this question is asked

Every Java server framework that handles thousands of connections, from Netty to Tomcat's NIO connector, is built on this loop. Interviewers ask about it because it shows whether we understand what "non-blocking" really means, and because the classic mistakes (forgetting to remove keys, leaving OP_WRITE switched on, assuming one read gives one message) cause real outages: busy loops at 100% CPU and corrupted messages. In this answer, we will recap why thread-per-connection runs out of steam, set up a selector, walk through the main loop line by line, look at interest sets and why OP_WRITE is special, and see how per-connection buffers deal with partial reads.

1A Quick Recap: Why One Thread per Connection Runs Out

With classic blocking I/O, socket.getInputStream().read() parks the calling thread until bytes arrive. If a client is idle for a minute, its thread sleeps for a minute. So a server that wants 10,000 open connections needs 10,000 platform threads, and each one reserves a stack (often 1 MB of address space) and costs the operating system scheduling work.

Non-blocking I/O changes the contract. A channel in non-blocking mode returns immediately: read() gives back the bytes that are already there, possibly 0, and never waits. That alone would force us to poll every channel in a loop, which wastes CPU. The missing piece is a way to ask the kernel "which of these 10,000 sockets has something for me right now?" That is exactly what a Selector is: a Java wrapper over the operating system's readiness API, epoll on Linux, kqueue on macOS and the BSDs, and an equivalent on Windows.

2Registering Channels and Their Interest Sets

We open a server channel, switch it to non-blocking mode (a selector refuses blocking channels with IllegalBlockingModeException), and register it. Registration returns a SelectionKey, the object that ties one channel to one selector. The key holds two sets of flags: the interest set, the operations we want to hear about, and the ready set, the operations the kernel said are ready on the last select.

Java
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress(8080));
server.configureBlocking(false); // required before register()
Selector selector = Selector.open(); // epoll/kqueue under the hood
SelectionKey serverKey = server.register(selector, SelectionKey.OP_ACCEPT);
System.out.println(serverKey.interestOps()); // 16: OP_ACCEPT
The four interest operations
OperationReady meansTypical channel
OP_ACCEPT (16)a new connection is queuedServerSocketChannel
OP_CONNECT (8)an outgoing connect finished or failedclient SocketChannel
OP_READ (1)bytes are waiting, or the peer closedSocketChannel
OP_WRITE (4)the send buffer has free spaceSocketChannel, only when output is pending

There are four operations. OP_ACCEPT means a new connection is waiting on a server socket. OP_CONNECT means an outgoing connect has finished. OP_READ means there are bytes to read, or the peer has closed. OP_WRITE means the socket's send buffer has room. A key can also carry an attachment, any object we like, and that is where we keep the per-connection state.

3Walking Through the Main Loop

Here is the whole event loop. It runs on a single thread and serves every connection.

Java
while (true) {
selector.select(); // blocks until at least one key is ready
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove(); // the selector never removes it for us
if (!key.isValid()) continue; // channel closed meanwhile
if (key.isAcceptable()) {
SocketChannel ch = server.accept(); // never blocks here: a client is waiting
ch.configureBlocking(false);
ch.register(selector, SelectionKey.OP_READ, new Conn()); // Conn is the attachment
} else if (key.isReadable()) {
read(key);
} else if (key.isWritable()) {
write(key);
}
}
}
Step throughOne pass of the selector loop
  1. select()blocks until the kernel reports a ready channel
  2. Take the next selected keyand remove it from the set
  3. Is it acceptable?
    Yesaccept, set non-blocking, register for OP_READNocheck the next flag
  4. Is it readable?
    Yesread into the connection's buffer, parse whole messagesNocheck the next flag
  5. Is it writable?
    Yeswrite pending bytes; drop OP_WRITE when the queue is emptyNoignore
  6. More keys?
    Yeshandle the next keyNoback to select()

6 steps in order. Play them, or step through them one at a time.

Notice the it.remove() line. The selected-key set is only ever added to by select(); the selector does not clear it. If we forget to remove a key, the next pass sees it again even though nothing new happened, and our handler runs a second time on a socket that has nothing to read. Since Java 11 there is also selector.select(key -> handle(key)), which passes each ready key to a callback and manages the set for us.

The reason one thread can serve thousands of connections is that it only ever does work that cannot block: select() is the one place where it waits, and it waits for all channels at once. Each handler must therefore be short. A handler that calls a slow database or sleeps would stall every other connection on this loop, which is why real servers hand slow work to another pool.

4Why OP_WRITE Must Only Be Switched On While Output Is Pending

A socket is almost always writable: its kernel send buffer is usually nearly empty. If we register OP_WRITE permanently, select() returns immediately on every call because that key is always ready, and the loop spins at 100% CPU doing nothing. So the rule is to write directly when we have a response, and only if the socket did not accept everything do we turn OP_WRITE on. When the queue has drained, we turn it off again.

Java
void send(SelectionKey key, ByteBuffer data) throws IOException {
Conn c = (Conn) key.attachment();
c.out.add(data);
write(key);
}
void write(SelectionKey key) throws IOException {
Conn c = (Conn) key.attachment();
SocketChannel ch = (SocketChannel) key.channel();
while (!c.out.isEmpty()) {
ByteBuffer head = c.out.peek();
ch.write(head); // may write only part of it, or 0 bytes
if (head.hasRemaining()) { // send buffer full: wait for the kernel
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
return;
}
c.out.poll();
}
key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); // nothing left: stop asking
}

So OP_WRITE is not "I want to write"; it is "tell me when the slow client has made room". That one change is the difference between a server that idles at 1% CPU and one that burns a core.

5Partial Reads and Per-Connection Buffers

TCP is a stream of bytes, not of messages. A 2,000-byte request may arrive as one read of 2,000 bytes, two reads of 1,000, or a read that also contains the start of the next request. So each connection keeps its own input buffer in the attachment, and we only process complete messages.

Java
void read(SelectionKey key) throws IOException {
Conn c = (Conn) key.attachment();
SocketChannel ch = (SocketChannel) key.channel();
int n = ch.read(c.in); // 0..capacity bytes, or -1 at end of stream
if (n == -1) { key.cancel(); ch.close(); return; }
c.in.flip(); // switch the buffer to reading
while (c.in.remaining() >= 4) { // our protocol: 4-byte length, then the body
int len = c.in.getInt(c.in.position());
if (c.in.remaining() < 4 + len) break; // body not complete yet: keep it
c.in.getInt();
byte[] body = new byte[len];
c.in.get(body);
handleMessage(key, body);
}
c.in.compact(); // keep the leftover bytes for the next read
}

The flip() and compact() pair is the heart of it. After a read, flip() lets us parse from the start; compact() moves any unfinished bytes to the front so the next read appends to them. A connection whose message is half-received simply waits for the next OP_READ with its partial data safely stored, while the thread serves other connections.

6Follow-up questions

Why do frameworks like Netty use several event loop threads?

One selector loop runs on one thread, so it can use at most one CPU core. Netty creates a group of event loops, by default twice the number of cores, each with its own selector. A new connection is assigned to one loop and stays there for its whole life, so its handlers always run on the same thread and need no locks. Usually one small group accepts connections and a larger group does the reads and writes. That spreads the work across cores while keeping each connection single-threaded.

What does select() return, and can it return 0?

It returns the number of keys whose ready set was updated. It can return 0 when another thread calls selector.wakeup(), when the thread is interrupted, or after a timeout with select(long). The loop should simply iterate whatever is in the selected set and carry on.

How do other threads hand work to a selector thread safely?

Calling register() or changing interest ops from another thread can block or race with a select() in progress. The common pattern is a concurrent task queue: other threads add a task and call selector.wakeup(), and the loop runs queued tasks after each select(). Netty's event loop works exactly this way.

7Conclusion

In this answer, we saw that a Selector turns many non-blocking channels into one stream of readiness events. Channels are registered with interest sets, select() blocks in epoll or kqueue until something is ready, and the loop handles each selected key and removes it. OP_WRITE belongs in the interest set only while output is waiting, otherwise the loop spins, and because reads can be partial, each connection keeps its own buffer and only complete messages are processed.

What to say in the interviewAbout 90 seconds aloud

Open with

A Selector is Java's wrapper around the OS readiness API, epoll on Linux or kqueue on Mac. I put each channel in non-blocking mode and register it with an interest set: OP_ACCEPT on the server channel, OP_READ on accepted sockets.

Then, if they want more

The SelectionKey I get back links the channel to the selector and can carry an attachment, which is where I keep per-connection state. The loop is: call select(), which blocks until at least one channel is ready; iterate selectedKeys; remove each key, because the selector never clears that set; then accept, read or write depending on the ready flags.

Since every handler is non-blocking, one thread can serve thousands of mostly idle connections. Two details matter in practice. First, OP_WRITE: a socket is almost always writable, so if I leave OP_WRITE on, select returns immediately forever and the loop burns a core.

I write directly, and only register OP_WRITE when the send buffer is full, then clear it once the queue drains. Second, TCP has no message boundaries, so a read may give me half a message or one and a half. Each connection has its own ByteBuffer; I flip it, parse only complete frames, and compact the rest.

For more cores, frameworks like Netty run several event loops, each with its own selector, and pin each connection to one loop so its code never needs locks.

About this answer

Last updated
12 November 2026
Versions it names
Java 11
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does a Selector enable one thread to serve many connections? Describe the main loop...": https://scrivio-interview-library.netlify.app/java/io-and-nio/17aebe7bfa/