Java NIO Selectors: Non-blocking Network Servers
A Selector lets one thread watch many non-blocking sockets and serve whichever are ready. A complete line-based server on one thread, tested with 1,000 clients that send their messages in pieces, and measured against a virtual thread per connection on JDK 25.
Contents
Introduction
A server that talks to many clients spends most of its time waiting for them. The classic way to wait is one thread per connection. The thread calls read
A Selectorjava.nio.channels
Look at the picture. The selector watches five connections. Clients 2 and 4 have sent data, so when the thread calls select()
Since Java 21 there is a simpler way to serve many clients, a virtual thread per connection with plain blocking code. Selectors are still worth knowing, because frameworks use them underneath, and because writing one selector loop shows what non-blocking I/O really involves.
How selectors work
The selector passes the question to the operating system. On Linux the JDK uses epollkqueue
Each registration produces a SelectionKey
| Operation | Channel | Ready when |
|---|---|---|
OP_ACCEPT | ServerSocketChannel | A new connection is waiting for accept() |
OP_CONNECT | SocketChannel | A non-blocking connect can be finished with finishConnect() |
OP_READ | SocketChannelDatagramChannel | Data, or the end of the stream, can be read |
OP_WRITE | SocketChannelDatagramChannel | There is room in the send buffer, which is almost always |
Every program below uses only the JDK and was run on JDK 25 under Linux, on a machine with 2 CPUs.
Selector rules, step by step
Most selector bugs come from a few rules about when keys are reported. The examples share two small helper classes. LoopbackPair
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
// Two connected sockets on this machine: the client's end and the server's end
public class LoopbackPair implements AutoCloseable {
final ServerSocketChannel server;
final SocketChannel client; // the end a client program holds
final SocketChannel accepted; // the end the server works with
LoopbackPair() throws IOException {
server = ServerSocketChannel.open()
.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
client = SocketChannel.open(server.getLocalAddress());
accepted = server.accept();
accepted.configureBlocking(false); // only non-blocking channels can be registered
}
@Override
public void close() throws IOException {
accepted.close();
client.close();
server.close();
}
}
The second helper, OpsREAD
import java.nio.channels.SelectionKey;
// Turns a set of SelectionKey operation bits into readable names
public class Ops {
static String names(int ops) {
StringBuilder sb = new StringBuilder();
if ((ops & SelectionKey.OP_ACCEPT) != 0) {
sb.append("ACCEPT ");
}
if ((ops & SelectionKey.OP_CONNECT) != 0) {
sb.append("CONNECT ");
}
if ((ops & SelectionKey.OP_READ) != 0) {
sb.append("READ ");
}
if ((ops & SelectionKey.OP_WRITE) != 0) {
sb.append("WRITE ");
}
return sb.toString().trim();
}
}
The first example registers a server channel for OP_ACCEPT
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class AcceptReady {
public static void main(String[] args) throws Exception {
try (Selector selector = Selector.open();
ServerSocketChannel server = ServerSocketChannel.open()) {
server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
server.configureBlocking(false);
SelectionKey key = server.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("selector implementation: " + selector.getClass().getSimpleName());
System.out.println("ready keys before any client: " + selector.selectNow());
try (SocketChannel client = SocketChannel.open(server.getLocalAddress())) {
int ready = selector.select(1000);
System.out.println("ready keys after a client connects: " + ready
+ ", ready ops: " + Ops.names(key.readyOps()));
}
}
}
}
Running it prints:
selector implementation: EPollSelectorImpl
ready keys before any client: 0
ready keys after a client connects: 1, ready ops: ACCEPT
On Linux the selector is EPollSelectorImplselectNow()selectACCEPTaccept()
The next example sends data over a connected pair and checks three rules:
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
public class ReadyRules {
public static void main(String[] args) throws Exception {
try (Selector selector = Selector.open(); LoopbackPair pair = new LoopbackPair()) {
SelectionKey key = pair.accepted.register(selector, SelectionKey.OP_READ);
pair.client.write(ByteBuffer.wrap("hello".getBytes()));
// Rule 1: the selector adds keys to selectedKeys() but never removes them
System.out.println("select() after data: " + selector.select(1000));
pair.accepted.read(ByteBuffer.allocate(16));
System.out.println("after reading, selectNow(): " + selector.selectNow()
+ ", but selectedKeys() still holds " + selector.selectedKeys().size());
selector.selectedKeys().clear();
// Rule 2: a channel with unread data is reported again and again
pair.client.write(ByteBuffer.wrap("again".getBytes()));
long start = System.nanoTime();
for (int i = 1; i <= 3; i++) {
int ready = selector.select(1000);
selector.selectedKeys().clear(); // removed, but not read
System.out.println("select() without reading, call " + i + ": " + ready);
}
System.out.println("the three select(1000) calls took "
+ (System.nanoTime() - start) / 1000000 + " ms in total");
// Rule 3: closing the channel cancels its key
pair.accepted.close();
System.out.println("key valid after the channel is closed: " + key.isValid());
}
}
}
Running it prints:
select() after data: 1
after reading, selectNow(): 0, but selectedKeys() still holds 1
select() without reading, call 1: 1
select() without reading, call 2: 1
select() without reading, call 3: 1
the three select(1000) calls took 0 ms in total
key valid after the channel is closed: false
Keys stay selected until you remove them. The selectselectedKeys()selectNow()selectedKeys()
An unread channel stays ready. After more data arrived, three calls of select(1000)
Closing a channel cancels its key. After close()isValid()
The last rule is about waking a selector up. A select()wakeup()
import java.nio.channels.Selector;
public class WakeupDemo {
public static void main(String[] args) throws Exception {
try (Selector selector = Selector.open()) {
Thread.ofVirtual().start(() -> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
return;
}
selector.wakeup(); // called from another thread
});
long start = System.nanoTime();
int keys = selector.select(); // nothing registered: would wait forever
long ms = (System.nanoTime() - start) / 1000000;
System.out.println("select() returned " + keys + " keys after " + ms + " ms");
}
}
}
Running it prints:
select() returned 0 keys after 203 ms
Nothing was registered, so select()wakeup()
The server
The minimal selector loop on the
- Partial reads: one
can return half a line, or a line and a half. Each connection needs its own input buffer that keeps an incomplete line until the rest arrives.read - Partial writes: a non-blocking
sends only what fits in the socket's send buffer. Each connection needs a queue of replies still to send, and the server asks forwrite only while that queue is not empty. Asking for it all the time would wake the selector constantly, because a socket is almost always writable.OP_WRITE
That state lives in a small class, Conn
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
// What the server remembers about one connection between reads
public class Conn {
final ByteBuffer in = ByteBuffer.allocate(64); // received bytes, maybe half a line
final ArrayDeque<ByteBuffer> out = new ArrayDeque<>(); // replies not fully sent yet
}
The server attaches each connection's ConnSelectionKeyselectLineServerok:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedSelectorException;
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.Iterator;
// A one-thread server: reads lines that may arrive in pieces and answers each with "ok:<line>"
public class LineServer implements Runnable {
final Selector selector;
final ServerSocketChannel server;
volatile int linesHandled;
volatile int maxOpen;
int open;
LineServer() throws IOException {
selector = Selector.open();
server = ServerSocketChannel.open().bind(new InetSocketAddress("127.0.0.1", 0), 2048);
server.configureBlocking(false);
server.register(selector, SelectionKey.OP_ACCEPT);
}
int port() throws IOException {
return ((InetSocketAddress) server.getLocalAddress()).getPort();
}
// run(), accept(), read() and write() go here, as shown below
}
The backlog of 2,048 in bindlinesHandledmaxOpenrunselect()
@Override
public void run() {
try {
while (selector.isOpen()) {
selector.select();
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove(); // rule 1: remove it yourself
if (!key.isValid()) {
continue;
}
if (key.isAcceptable()) {
accept();
} else if (key.isReadable()) {
read(key);
} else if (key.isWritable()) {
write(key);
}
}
}
} catch (IOException | ClosedSelectorException e) {
// the selector was closed: shut down
}
}
The acceptOP_READConnreadcompact()
void accept() throws IOException {
SocketChannel c = server.accept();
c.configureBlocking(false);
c.register(selector, SelectionKey.OP_READ, new Conn()); // the Conn rides on the key
maxOpen = Math.max(maxOpen, ++open);
}
void read(SelectionKey key) throws IOException {
SocketChannel c = (SocketChannel) key.channel();
Conn conn = (Conn) key.attachment();
if (c.read(conn.in) == -1) { // the client closed
key.cancel();
c.close();
open--;
return;
}
conn.in.flip();
// Take out every complete line; a partial line stays for the next read
for (int i = conn.in.position(); i < conn.in.limit(); i++) {
if (conn.in.get(i) == '\n') {
byte[] line = new byte[i - conn.in.position()];
conn.in.get(line).get(); // the line, then its '\n'
String reply = "ok:" + new String(line, StandardCharsets.UTF_8) + "\n";
conn.out.add(StandardCharsets.UTF_8.encode(reply));
linesHandled++;
}
}
conn.in.compact();
if (!conn.out.isEmpty()) {
key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
}
Last, the writeOP_WRITEOP_READ
void write(SelectionKey key) throws IOException {
SocketChannel c = (SocketChannel) key.channel();
Conn conn = (Conn) key.attachment();
while (!conn.out.isEmpty()) {
ByteBuffer b = conn.out.peek();
c.write(b);
if (b.hasRemaining()) {
return; // socket full: wait for OP_WRITE
}
conn.out.poll();
}
key.interestOps(SelectionKey.OP_READ); // all sent: stop asking for OP_WRITE
}
Put the methods from the last three parts where the comment in the first part says, and you have the whole of LineServer.java
1,000 clients on one thread
To test the server, each client sends three lines and splits every line into two writes with a 1 ms pause between them, so the server really receives partial lines. It counts the replies that match its own lines. A latch makes every client wait until all of them are connected, so all connections are open at the same time:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
// A test client: sends three lines, each in two pieces, and counts the correct replies
public class PieceClient {
static int talk(int port, int id, CountDownLatch allConnected) throws Exception {
try (Socket s = new Socket(InetAddress.getLoopbackAddress(), port)) {
allConnected.countDown();
allConnected.await(); // start only when every client is connected
OutputStream out = s.getOutputStream();
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream(), StandardCharsets.UTF_8));
int correct = 0;
for (int m = 0; m < 3; m++) {
byte[] b = ("c" + id + "-m" + m + "\n").getBytes(StandardCharsets.UTF_8);
out.write(b, 0, 2); // the first two bytes
out.flush();
Thread.sleep(1);
out.write(b, 2, b.length - 2); // the rest, ending with '\n'
out.flush();
if (in.readLine().equals("ok:c" + id + "-m" + m)) {
correct++;
}
}
return correct;
}
}
}
The test starts the server on one platform thread and 1,000 clients on virtual threads:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class ManyClients {
public static void main(String[] args) throws Exception {
LineServer server = new LineServer();
Thread selectorThread = Thread.ofPlatform().name("selector").start(server);
int clients = 1000;
CountDownLatch allConnected = new CountDownLatch(clients);
CountDownLatch done = new CountDownLatch(clients);
AtomicInteger correctReplies = new AtomicInteger();
for (int i = 0; i < clients; i++) {
int id = i;
Thread.ofVirtual().start(() -> {
try {
correctReplies.addAndGet(PieceClient.talk(server.port(), id, allConnected));
} catch (Exception e) {
System.out.println("client " + id + ": " + e);
} finally {
done.countDown();
}
});
}
done.await();
System.out.println("connections open at the same time (peak): " + server.maxOpen);
System.out.println("lines handled by the server: " + server.linesHandled);
System.out.println("correct replies received: " + correctReplies.get());
server.selector.close();
selectorThread.join();
}
}
Running it prints:
connections open at the same time (peak): 1000
lines handled by the server: 3000
correct replies received: 3000
One selector thread held 1,000 open connections and handled all 3,000 lines. Every client got its own correct replies, even though its lines arrived in pieces, mixed in with other clients' data.
OP_WRITE and partial writes, measured
The server asks for OP_WRITEselect(50)
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
public class WriteWakeups {
// How often select(50) returns in 200 ms on a connection where nothing happens
static int selectReturns(int interest) throws Exception {
try (Selector selector = Selector.open(); LoopbackPair pair = new LoopbackPair()) {
pair.accepted.register(selector, interest);
int count = 0;
long end = System.nanoTime() + 200000000L;
while (System.nanoTime() < end) {
selector.select(50);
selector.selectedKeys().clear();
count++;
}
return count;
}
}
public static void main(String[] args) throws Exception {
int readOnly = selectReturns(SelectionKey.OP_READ);
int readWrite = selectReturns(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
System.out.printf("OP_READ only: %,9d select() returns in 200 ms%n", readOnly);
System.out.printf("OP_READ | OP_WRITE: %,9d select() returns in 200 ms%n", readWrite);
}
}
Running it prints:
OP_READ only: 4 select() returns in 200 ms
OP_READ | OP_WRITE: 301,141 select() returns in 200 ms
With OP_READselect(50)OP_WRITE
The other half is the partial write. This program sends 20 MB in one non-blocking write
import java.nio.ByteBuffer;
public class PartialWrite {
public static void main(String[] args) throws Exception {
try (LoopbackPair pair = new LoopbackPair()) {
ByteBuffer big = ByteBuffer.allocate(20000000); // 20 MB to send
int written = pair.accepted.write(big); // non-blocking: no waiting
System.out.printf("write() took %,d of %,d bytes; %,d are still in the buffer%n",
written, big.capacity(), big.remaining());
}
}
}
Running it prints:
write() took 3,919,872 of 20,000,000 bytes; 16,080,128 are still in the buffer
The call took 3,919,872 bytes, as much as fitted in the operating system's buffers at that moment, and left the rest in the ByteBufferOP_WRITELineServer.writewrite
Selectors and other threads
The server above does everything on one thread. Real servers often hand slow work, such as a database call, to other threads, and those threads need to give their replies back to the selector. Which parts of a selector can other threads use? The
Older guides also warn that registerselect()register
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
public class RegisterWhileSelecting {
public static void main(String[] args) throws Exception {
try (Selector selector = Selector.open();
ServerSocketChannel server = ServerSocketChannel.open()) {
Thread selectorThread = Thread.ofPlatform().start(() -> {
try {
selector.select(3000); // waits up to 3 seconds
} catch (Exception e) {
throw new RuntimeException(e);
}
});
Thread.sleep(300); // select() is now waiting
server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
server.configureBlocking(false);
long start = System.nanoTime();
server.register(selector, SelectionKey.OP_ACCEPT); // from this thread
System.out.println("register() during select() took "
+ (System.nanoTime() - start) / 1000000 + " ms");
selector.wakeup();
selectorThread.join();
}
}
}
Running it prints:
register() during select() took 1 ms
The call returned in 1 ms while the other thread was still inside select(3000)wakeup()
The usual design still keeps all key changes on the selector thread. Other threads put their work in a queue and call wakeup()
Clients can use the same machinery. A non-blocking SocketChannel.connectOP_CONNECTfinishConnect()
Selector or virtual threads?
Since Java 21, a LineServer
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
// The same protocol as LineServer ("x" -> "ok:x"), with one virtual thread per connection
public class VirtualThreadServer {
static ServerSocket start() throws IOException {
ServerSocket ss = new ServerSocket(0, 2048, InetAddress.getLoopbackAddress());
Thread.ofVirtual().start(() -> {
while (!ss.isClosed()) {
try {
Socket s = ss.accept();
Thread.ofVirtual().start(() -> serve(s));
} catch (IOException e) {
return; // the server socket was closed
}
}
});
return ss;
}
static void serve(Socket s) {
try (s; BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream(), StandardCharsets.UTF_8));
PrintWriter out = new PrintWriter(s.getOutputStream(), true, StandardCharsets.UTF_8)) {
String line;
while ((line = in.readLine()) != null) { // blocks; the virtual thread parks
out.println("ok:" + line);
}
} catch (IOException e) {
// the client went away
}
}
}
There are no buffers to manage, no partial lines to put back together and no write queue. The calls to readLineprintln
To compare the two servers, LoadTest
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
// 500 clients, each sending 200 lines and waiting for each reply; returns the time in ms
public class LoadTest {
static long run(int port) throws Exception {
int clients = 500;
AtomicInteger ok = new AtomicInteger();
CountDownLatch done = new CountDownLatch(clients);
long start = System.nanoTime();
for (int i = 0; i < clients; i++) {
int id = i;
Thread.ofVirtual().start(() -> {
try (Socket s = new Socket(InetAddress.getLoopbackAddress(), port)) {
s.setTcpNoDelay(true);
OutputStream out = s.getOutputStream();
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream(), StandardCharsets.UTF_8));
for (int m = 0; m < 200; m++) {
out.write(("c" + id + "m" + m + "\n").getBytes(StandardCharsets.UTF_8));
if (in.readLine().equals("ok:c" + id + "m" + m)) {
ok.incrementAndGet();
}
}
} catch (Exception e) {
System.out.println("client " + id + ": " + e);
} finally {
done.countDown();
}
});
}
done.await();
if (ok.get() != 100000) {
throw new AssertionError("only " + ok.get() + " correct replies");
}
return (System.nanoTime() - start) / 1000000;
}
}
The program below runs the load test against both servers in turn for four rounds. The first round is a warm-up, and it keeps the best time of the other three:
import java.net.ServerSocket;
public class CompareServers {
public static void main(String[] args) throws Exception {
LineServer selectorServer = new LineServer();
Thread selectorThread = Thread.ofPlatform().start(selectorServer);
try (ServerSocket virtualServer = VirtualThreadServer.start()) {
long bestSelector = Long.MAX_VALUE;
long bestVirtual = Long.MAX_VALUE;
for (int round = 0; round < 4; round++) { // round 0 is a warm-up
long a = LoadTest.run(selectorServer.port());
long b = LoadTest.run(virtualServer.getLocalPort());
if (round > 0) {
bestSelector = Math.min(bestSelector, a);
bestVirtual = Math.min(bestVirtual, b);
}
}
System.out.println("500 clients x 200 lines = 100,000 replies from each server");
System.out.printf("selector server, one thread: %5d ms%n", bestSelector);
System.out.printf("virtual thread per connection: %5d ms%n", bestVirtual);
}
selectorServer.selector.close();
selectorThread.join();
}
}
Running it prints:
500 clients x 200 lines = 100,000 replies from each server
selector server, one thread: 873 ms
virtual thread per connection: 706 ms
Both servers answered all 100,000 lines correctly, and on this 2-CPU machine with JDK 25 the virtual-thread server was faster, 706 ms against 873 ms. Four more runs of the program gave the same order every time, with the virtual-thread server taking 15% to 30% less time. One reason fits the design. The selector server does all its work on one thread, so it can use at most one CPU, while virtual threads run on as many carrier threads as there are CPUs. The clients run on the same machine, so this compares overhead, not capacity.
| Selector (NIO) | Virtual thread per connection | |
|---|---|---|
| Code style | Event loop with explicit state per connection | Plain blocking code |
| Partial reads and writes | Handled by your code | Handled by blocking streams |
| Threads | One or a few | One cheap virtual thread per connection |
| Available since | Java 1.4 | Java 21 |
On Java 21 and later, a virtual thread per connection is the simpler choice for most servers, and for the waiting, the JDK uses the same operating system mechanism underneath, epoll