Java NIO Selectors: Building an Event-Loop Server
A complete single-threaded NIO server: Selector, SelectionKey interest and ready sets, accepting and reading without blocking, partial reads with compact(), partial writes with OP_WRITE, offloading slow work, and waking the loop safely from other threads.
kvi5hnuCode Sprout team member9 min readOn this page
Article 42 ended with a non-blocking channel that had to be polled in a loop. A Selector removes the polling. You register many channels with one selector, call select(), and the thread sleeps until the operating system reports that some of those channels are ready: a connection to accept, bytes to read, room to write. The thread then handles exactly those channels and goes back to sleep. That loop is an event loop, and it's the core of Netty, Vert.x and every other NIO-based server.
The pieces
Selector: created withSelector.open(). It's backed by the OS's readiness API:epollon Linux,kqueueon macOS, and awepoll-based implementation on Windows since Java 17.SelectableChannel.register(selector, ops, attachment): adds a channel, which must be in non-blocking mode, and returns aSelectionKey.- Interest set: the operations you want to be told about:
OP_ACCEPT,OP_READ,OP_WRITEandOP_CONNECT. You change it withinterestOps(...). - Ready set: what the OS reported as ready on the last
select(), checked withisAcceptable(),isReadable()andisWritable(). - Attachment: any object stored on the key. Servers keep per-connection state there, because a handler is called many times for one connection.
- Selected-key set:
selector.selectedKeys()holds the keys that became ready. The selector only adds to it, so the loop must remove each key after handling it.
A quote server on one thread
The server speaks a line protocol: quote LIS-OSL is answered at once, and slow LIS-TOS needs a 300 ms back-end call. All socket I/O happens on one platform thread named event-loop. The clients are ordinary blocking sockets on virtual threads.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Solution {
/** A line-based quote server: one event-loop thread does all socket I/O. */
static final class QuoteServer implements AutoCloseable {
/** Per-connection state: bytes read so far, and replies waiting to be written. */
static final class Connection {
final ByteBuffer in = ByteBuffer.allocate(256);
final Queue<ByteBuffer> out = new ArrayDeque<>();
}
private final Selector selector = Selector.open();
private final ServerSocketChannel server = ServerSocketChannel.open();
private final Queue<Runnable> loopTasks = new ConcurrentLinkedQueue<>(); // work for the loop thread
private final ExecutorService workers = Executors.newVirtualThreadPerTaskExecutor();
final Set<String> ioThreads = ConcurrentHashMap.newKeySet();
private final Thread loop;
private volatile boolean running = true;
QuoteServer() throws IOException {
server.bind(new InetSocketAddress("localhost", 0));
server.configureBlocking(false);
server.register(selector, SelectionKey.OP_ACCEPT);
loop = Thread.ofPlatform().name("event-loop").start(this::runLoop);
}
int port() throws IOException {
return ((InetSocketAddress) server.getLocalAddress()).getPort();
}
private void runLoop() {
try {
while (running) {
selector.select(); // sleep until a channel is ready or wakeup()
Runnable task;
while ((task = loopTasks.poll()) != null) task.run();
Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
while (keys.hasNext()) {
SelectionKey key = keys.next();
keys.remove(); // the selected set isn't cleared for us
try {
if (key.isAcceptable()) accept();
else if (key.isReadable()) read(key);
else if (key.isWritable()) write(key);
} catch (IOException e) {
close(key);
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void accept() throws IOException {
SocketChannel client = server.accept(); // non-blocking: null if nobody is waiting
if (client == null) return;
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ, new Connection());
}
private void read(SelectionKey key) throws IOException {
ioThreads.add(Thread.currentThread().getName());
SocketChannel channel = (SocketChannel) key.channel();
Connection conn = (Connection) key.attachment();
if (channel.read(conn.in) == -1) { close(key); return; }
conn.in.flip();
int lineStart = 0;
for (int i = conn.in.position(); i < conn.in.limit(); i++) {
if (conn.in.get(i) == '\n') { // a complete request line
byte[] line = new byte[i - lineStart];
conn.in.get(lineStart, line);
handle(key, new String(line, StandardCharsets.UTF_8));
lineStart = i + 1;
}
}
conn.in.position(lineStart);
conn.in.compact(); // keep a partial line for the next read
}
private void handle(SelectionKey key, String request) {
if (request.startsWith("slow ")) {
String route = request.substring(5);
workers.submit(() -> { // never block the event loop
Thread.sleep(300); // a slow back-end call
String reply = quote(route);
loopTasks.add(() -> reply(key, reply)); // only the loop thread touches keys
selector.wakeup();
return null;
});
} else {
reply(key, quote(request.substring("quote ".length())));
}
}
static String quote(String route) {
return route + " " + (100 + route.chars().sum() % 400); // a made-up fare
}
private void reply(SelectionKey key, String text) {
if (!key.isValid()) return; // the client has gone
Connection conn = (Connection) key.attachment();
conn.out.add(ByteBuffer.wrap((text + "\n").getBytes(StandardCharsets.UTF_8)));
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
}
private void write(SelectionKey key) throws IOException {
ioThreads.add(Thread.currentThread().getName());
SocketChannel channel = (SocketChannel) key.channel();
Connection conn = (Connection) key.attachment();
while (!conn.out.isEmpty()) {
ByteBuffer buf = conn.out.peek();
channel.write(buf);
if (buf.hasRemaining()) return; // socket buffer full: wait for OP_WRITE
conn.out.poll();
}
key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); // nothing left to send
}
private void close(SelectionKey key) {
key.cancel();
try { key.channel().close(); } catch (IOException ignored) { }
}
@Override public void close() throws IOException {
running = false;
selector.wakeup();
try {
loop.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
workers.close();
for (SelectionKey key : selector.keys()) key.channel().close();
selector.close();
}
}
// ---------- clients (plain blocking sockets on virtual threads) ----------
static String ask(int port, String request) throws IOException {
try (var socket = new Socket("localhost", port);
var in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8))) {
socket.getOutputStream().write((request + "\n").getBytes(StandardCharsets.UTF_8));
return in.readLine();
}
}
public static void main(String[] args) throws Exception {
try (var server = new QuoteServer(); var clients = Executors.newVirtualThreadPerTaskExecutor()) {
int port = server.port();
// 1. A request that arrives in two pieces
try (var socket = new Socket("localhost", port);
var in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8))) {
OutputStream out = socket.getOutputStream();
out.write("quote LIS".getBytes(StandardCharsets.UTF_8));
out.flush();
Thread.sleep(100);
out.write("-OSL\n".getBytes(StandardCharsets.UTF_8));
System.out.println("1. split request answered: " + in.readLine());
}
// 2. A slow request doesn't hold up a fast one
List<String> finished = new CopyOnWriteArrayList<>();
Future<?> slow = clients.submit(() -> finished.add("slow: " + ask(port, "slow LIS-TOS")));
Thread.sleep(50);
Future<?> fast = clients.submit(() -> finished.add("fast: " + ask(port, "quote OSL-TOS")));
slow.get();
fast.get();
System.out.println("2. replies in order of arrival: " + finished);
// 3. Many concurrent clients, one I/O thread
List<Future<Boolean>> results = new ArrayList<>();
for (int c = 0; c < 200; c++) {
String route = "R" + c;
results.add(clients.submit(() -> ask(port, "quote " + route).equals(QuoteServer.quote(route))));
}
int correct = 0;
for (Future<Boolean> r : results) if (r.get()) correct++;
System.out.println("3. 200 concurrent clients, correct replies: " + correct);
System.out.println(" socket reads and writes ran on: " + server.ioThreads);
}
}
}
Output:
1. split request answered: LIS-OSL 215
2. replies in order of arrival: [fast: OSL-TOS 229, slow: LIS-TOS 223]
3. 200 concurrent clients, correct replies: 200
socket reads and writes ran on: [event-loop]
One thread served 203 connections, and a slow request didn't delay a fast one. Here's how each part works.
Accepting
The server channel is registered for OP_ACCEPT. When a client connects, accept() returns its SocketChannel without blocking, or null if another thread or event got there first. The new channel is switched to non-blocking mode and registered for OP_READ, with a fresh Connection as its attachment.
Reading: requests arrive in pieces
TCP delivers a byte stream, not messages. One read can return half a request, or two and a half requests. Client 1 sent quote LIS, waited 100 ms, and then sent -OSL\n, so the first read had no complete line. The server:
- reads whatever is available into the connection's buffer,
flip()s it and scans for\n, handling every complete line,- sets the position after the last complete line and calls
compact(), keeping the partial line at the front for the next read.
A read that returns -1 means the client closed the connection, so the server cancels the key and closes the channel. The fixed 256-byte buffer is a simplification: a request longer than that could never complete, so a real server must either grow the buffer or reject oversized requests.
Writing: only when there's something to send
A channel is almost always writable, so leaving OP_WRITE in the interest set makes select() return immediately, again and again: a busy loop. The server turns OP_WRITE on only when a reply is queued, and off again when the queue is empty. write may also send only part of a buffer when the socket's send buffer is full. The loop then stops and waits for the next OP_WRITE, and the unsent bytes stay in the buffer at its position.
Never block the loop
Every connection depends on the loop thread. If the handler for slow slept for 300 ms on that thread, all 200 other clients would wait. Instead, handle passes the slow call to a worker (here a virtual thread). In run 2, the fast request arrived 50 ms after the slow one and was answered first.
Getting results back to the loop
The worker can't simply write to the channel: two threads writing to one channel would interleave bytes, and the connection state isn't thread-safe. So the worker:
- puts a task (
reply(key, ...)) into a concurrent queue that only the loop thread drains, - calls
selector.wakeup(), which makes a blockedselect()return immediately.
The loop runs queued tasks right after select() returns, and those tasks set OP_WRITE. Everything that touches keys and connection state stays on one thread, so none of it needs locks.
About thread safety: SelectionKey methods can be called from any thread, and since Java 11 an interest-set change made during select() no longer blocks the caller. But key.interestOps(key.interestOps() | OP_WRITE) is a read-modify-write, and two threads doing it at once can lose an update. Java 11 added the atomic interestOpsOr and interestOpsAnd for that case. A change also only takes effect on the next select(), so another thread must still call wakeup(). Keeping all key changes on the loop thread, as here, avoids both issues.
What the design costs
The server works, but compare it with the blocking handler of article 42, which was eight lines long:
- A request's progress lives in a state object (
Connection), not in local variables. - Framing (partial lines, oversized requests) and flow control (partial writes,
OP_WRITE) are your problem. - Anything slow must be offloaded and its result marshalled back to the loop thread.
- Ordering needs care. If one connection sent
slow Athenquote Bwithout waiting, this server would answer B first. A protocol that requires in-order replies, such as HTTP/1.1 pipelining, needs a per-connection queue of pending replies, released in request order. - One bug in a handler, such as an accidental blocking call or an exception that escapes the loop, affects every connection.
That's why almost nobody writes raw selector code. Frameworks such as Netty provide the event loop, framing and back-pressure, and run your handlers as callbacks. Article 44 looks at that model, and at how application code talks to it.
What's current
- The NIO selector API is unchanged through Java 27, apart from Java 11's additions:
select(Consumer<SelectionKey>), which calls a consumer for each ready key and manages the selected set itself, and the atomicinterestOpsOrandinterestOpsAnd. - The JDK's virtual-thread pollers are event loops of exactly this kind. When a virtual thread blocks on a socket, the JDK registers the socket with a poller and unparks the thread when it's ready (article 23). With virtual threads, you get this event loop without writing it.
- Unix-domain socket channels (Java 16, JEP 380) work with selectors the same way as TCP channels.
Common questions
Why remove keys from selectedKeys() manually?
The selector adds keys to the set but never removes them. A key left in the set would be handled again on the next pass, even if the channel isn't ready any more. Use iterator.remove(), or select(Consumer), which handles the set for you.
How many threads should an event-loop server use? Usually one loop per CPU core, each with its own selector and a share of the connections. Netty's default is twice the number of cores. All of them must stay non-blocking.
Can I use one selector from several threads?
You can register channels and call wakeup() from other threads, but only one thread should run select() and handle its keys. Multi-threaded servers use one selector per loop thread.
What does select() return?
The number of keys whose ready set was updated, which can be 0 after wakeup(). Always check the selected-key set and the task queue rather than relying on the count.
Summary
- A
Selectorlets one thread wait for readiness on many non-blocking channels. Each registration returns aSelectionKeywith an interest set, a ready set and an attachment for per-connection state. - The event loop calls
select(), handles each selected key, and removes it from the selected set. - Reads deliver arbitrary pieces of the byte stream: buffer them, handle complete messages, and
compact()the rest. EnableOP_WRITEonly while replies are queued. - Never block the loop. Offload slow work, and get results back through a queue drained by the loop thread plus
selector.wakeup(). - Raw selector code puts framing, flow control and ordering in your hands, which is why frameworks wrap it, and why virtual threads, whose pollers do this internally, are simpler for request/response code.
Practice questions
A developer registers every client channel for OP_READ | OP_WRITE at accept time. The server works, but uses 100% of a CPU core while idle. Why?
Answer
Sockets are almost always writable, so every channel is "ready for write" on every select(), which returns immediately. The loop spins without doing useful work. Register for OP_WRITE only while a reply is waiting to be sent, and remove it when the write queue is empty.
A worker thread finishes a slow request and calls key.interestOps(key.interestOps() | SelectionKey.OP_WRITE) directly. The reply sometimes takes seconds to arrive. Why, and how do you fix it?
Answer
An interest change takes effect on the next selection operation. If the loop is blocked in select() with nothing else happening, it doesn't notice until some other event wakes it. The read-modify-write can also race with the loop thread's own changes. Queue the change for the loop thread and call selector.wakeup(), or at least use interestOpsOr and then wakeup().
One read call returns the bytes quote A\nquote B\nquo. What must the server do?
Answer
Handle the two complete requests, quote A and quote B, and keep quo for later: set the buffer's position after the last newline and compact(), so the partial request sits at the start of the buffer and the next read appends the rest after it.
Previous: Blocking vs Non-Blocking I/O in Java: Streams, NIO Channels and Buffers
Next: Event-Driven Java: Event Loops, Callbacks and CompletableFuture

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.