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.

CsCode.ioUpdated
Share

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 and blocks until its client sends something. That code is simple, but every waiting client holds a platform thread, and each platform thread reserves memory for its stack and needs scheduling by the operating system. Tying one to every idle client limits how many clients a machine can serve.

A Selector, in the java.nio.channels package, turns this around. Connections are switched to non-blocking mode and registered with one selector, and a single thread asks it which of them can make progress right now. The thread then reads from or writes to only those connections, and those calls never wait. Selectors came with NIO (JSR 51) in Java 1.4, in 2002, and Netty's standard transport, which many Java network frameworks build on, uses them.

A selector thread calls select() on a Selector that watches five client connections. Clients 2 and 4 have data waiting and are highlighted; select() hands back those two.

Look at the picture. The selector watches five connections. Clients 2 and 4 have sent data, so when the thread calls select(), it gets back those two and nothing else. Clients 1, 3 and 5 take none of the thread's time while they are quiet.

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 epoll, and on macOS kqueue, so one call can watch tens of thousands of sockets.

Each registration produces a SelectionKey, which holds the channel, the interest set (what you want to be told about), the ready set (what is possible now) and an optional attachment for per-connection state. These are the four operations a key can report:

Selection key operations
OperationChannelReady when
OP_ACCEPTServerSocketChannelA new connection is waiting for accept()
OP_CONNECTSocketChannelA non-blocking connect can be finished with finishConnect()
OP_READSocketChannel, DatagramChannelData, or the end of the stream, can be read
OP_WRITESocketChannel, DatagramChannelThere 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 opens a server socket on this machine, connects a client to it and accepts the connection, so each example starts with a connected pair:

Java
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, Ops, turns the operation bits of a key into names such as READ for printing:

Java
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 and connects one client:

Java
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:

Output
selector implementation: EPollSelectorImpl
ready keys before any client: 0
ready keys after a client connects: 1, ready ops: ACCEPT

On Linux the selector is EPollSelectorImpl. Before any client connected, selectNow() returned 0 at once. After the connection, select reported one ready key, and its ready set says ACCEPT, which means a connection is waiting for accept().

The next example sends data over a connected pair and checks three rules:

Java
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:

Output
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 select call returns the number of keys whose ready set changed and adds those keys to selectedKeys(), but the selector never takes them out again. After the data was read, selectNow() found nothing new, yet the set still held the key. A loop over selectedKeys() would handle that key again with nothing to read, which is why every selector loop removes each key as it handles it.

An unread channel stays ready. After more data arrived, three calls of select(1000) each returned 1 and took 0 ms together, though each one could have waited a second. Removing the key from the set does not help while the data is still there. A loop that skips a ready channel spins at full CPU.

Closing a channel cancels its key. After close(), the key reports isValid() as false, and the selector drops it during its next selection.

The last rule is about waking a selector up. A select() with no timeout waits until some channel is ready, and another thread can end that wait with wakeup():

Java
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:

Output
select() returned 0 keys after 203 ms

Nothing was registered, so select() would have waited forever. The call to wakeup() ended it after about 200 ms, with 0 keys. Servers use this when another thread has new work for the selector thread, such as a reply that a worker thread has prepared.

The server

The minimal selector loop on the NIO channels page reads each message in one call and writes each reply in one call. A real server cannot count on either:

  • Partial reads: one read 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.
  • Partial writes: a non-blocking write sends only what fits in the socket's send buffer. Each connection needs a queue of replies still to send, and the server asks for OP_WRITE 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.

That state lives in a small class, Conn, with one object per connection:

Java
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 Conn to its SelectionKey. When a key comes back from select, the one thread knows which buffer and which queue belong to that client. The server, LineServer, answers every line with ok: followed by the line. Its fields and setup come first:

Java
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 bind lets the operating system queue connections that arrive in a burst, instead of refusing them while the selector thread catches up. The counters linesHandled and maxOpen are only there for the test that follows. The loop in run waits in select(), then handles each ready key and removes it, as the first rule requires:

Java
@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 accept method registers each new connection for OP_READ with a new Conn attached. The read method adds the new bytes to that connection's buffer, takes out every complete line and queues a reply for each. Then compact() moves an incomplete line to the start of the buffer, where the next read continues it:

Java
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 write method sends queued replies until the queue is empty or the socket is full. If the socket is full, it returns and waits for the next OP_WRITE. Once everything is sent, it sets the key back to OP_READ only:

Java
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:

Java
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:

Java
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:

Output
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_WRITE only while it has replies queued. To see why, this program counts how often select(50) returns in 200 ms on a connection where nothing happens, first with read interest only and then with write interest added:

Java
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:

Output
OP_READ only:                 4 select() returns in 200 ms
OP_READ | OP_WRITE:     301,141 select() returns in 200 ms

With OP_READ only, select(50) returned 4 times, each time after its 50 ms timeout. With OP_WRITE added, it returned 301,141 times in the same 200 ms. A socket with free buffer space is always writable, so the selector thread spins and burns a whole CPU core doing nothing.

The other half is the partial write. This program sends 20 MB in one non-blocking write while the client reads nothing:

Java
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:

Output
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 ByteBuffer. A server has to keep that remainder, ask for OP_WRITE and continue when the selector reports room, as LineServer.write does. A server that does not check what is left after write silently cuts its replies short.

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 Selector documentation says that a selector and its key set are safe for use by several threads, but its selected-key set and cancelled-key set are not.

Older guides also warn that register from another thread blocks while the selector thread waits in select(). That was true before JDK 11, which changed register so that it can run during a selection. This program checks it:

Java
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:

Output
register() during select() took 1 ms

The call returned in 1 ms while the other thread was still inside select(3000). A new registration takes effect at the next selection, so the program calls wakeup() to start one.

The usual design still keeps all key changes on the selector thread. Other threads put their work in a queue and call wakeup(), and the selector thread takes the work from the queue and changes the keys itself. That keeps the selected-key set on one thread, where it is safe.

Clients can use the same machinery. A non-blocking SocketChannel.connect returns at once, the key reports OP_CONNECT when the connection is made or has failed, and finishConnect() completes it or throws the error. Frameworks such as Netty wrap all of this, together with buffer pooling and back-pressure (slowing down a sender that is faster than its receiver), which is why few applications write selector loops directly.

Selector or virtual threads?

Since Java 21, a virtual thread per connection is the simple alternative. The code is plain blocking code, as in TCP sockets, and while a virtual thread waits for its client, the JDK parks it instead of holding a platform thread. Here is the same line protocol as LineServer, written that way:

Java
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 readLine and println handle all of that.

To compare the two servers, LoadTest runs 500 clients that each send 200 lines and wait for every reply, 100,000 request-reply pairs in all, and returns the time taken:

Java
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:

Java
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:

Output
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.

Two ways to handle many connections
Selector (NIO)Virtual thread per connection
Code styleEvent loop with explicit state per connectionPlain blocking code
Partial reads and writesHandled by your codeHandled by blocking streams
ThreadsOne or a fewOne cheap virtual thread per connection
Available sinceJava 1.4Java 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 on Linux. Direct selector code still makes sense inside frameworks, and for protocols that need fine control over buffers and memory. Whichever you choose, measure with your own workload, because real requests do far more work than echoing a line.