Selector Multiplexes Ready Channels

One thread watches accept and read readiness for many sockets with Selector and SelectionKey, including the manual selectedKeys removal loop.

JavaResilience

Code

javasnippet
60 lines
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
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.util.Iterator;

public class SelectorMultiplexer {

    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocketChannel server = ServerSocketChannel.open();
        server.bind(new InetSocketAddress("127.0.0.1", 0));
        server.configureBlocking(false);
        // 一个 Selector 单线程盯住 accept 与多个连接的读就绪
        Selector selector = Selector.open();
        server.register(selector, SelectionKey.OP_ACCEPT);
        InetSocketAddress address = (InetSocketAddress) server.getLocalAddress();
        for (int i = 1; i <= 2; i++) {
            Thread.startVirtualThread(() -> probe(address, "probe-" + i));
        }

        int accepted = 0, closed = 0, bytes = 0;
        long deadline = System.currentTimeMillis() + 5_000;
        while (closed < 2 && System.currentTimeMillis() < deadline) {
            if (selector.select(200) == 0) {
                continue; // 超时醒来检查 deadline,避免永久阻塞
            }
            Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
            while (keys.hasNext()) {
                SelectionKey key = keys.next();
                keys.remove(); // selectedKeys 不自动清空,必须手动 remove
                if (key.isAcceptable()) {
                    SocketChannel client = server.accept();
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_READ);
                    accepted++;
                } else if (key.isReadable()) {
                    int n = ((SocketChannel) key.channel()).read(ByteBuffer.allocate(64));
                    bytes += Math.max(n, 0);
                    if (n < 0) { key.channel().close(); closed++; } // EOF:对端已关闭
                }
            }
        }
        System.out.println("accepted = " + accepted + ", bytes = " + bytes);
        selector.close();
        server.close();
    }

    // 客户端:连接后各写 8 字节("probe-N" + 换行)再关闭
    private static void probe(InetSocketAddress address, String message) {
        try (SocketChannel client = SocketChannel.open(address)) {
            client.write(ByteBuffer.wrap((message + "\n").getBytes()));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

How the snippet works

The moving parts are the class SelectorMultiplexer and the function probe.

The for (int i = 1; i <= 2; i++) loop only launches the two probe threads; the repeated work is the outer while (closed < 2 …) loop, which polls selector.select(200), walks the selectedKeys() iterator, and removes each key by hand before handling it. try-with-resources covers only the client channel in probe — main closes selector and server explicitly after the loop. UncheckedIOException is not an up-front state check: it is the wrapper probe throws when the client connection fails with an IOException, propagating that failure out of the virtual thread.

What to watch for

  • Nothing arrives from a registry; the language ships every API used.

Using it

The central declaration: private static void probe(InetSocketAddress address, String message)

Watch for these labels — accepted = — when the file runs.

There is 1 call inside main — probe — executed top to bottom.

Key statements

Thread.startVirtualThread(() -> probe(address, "probe-" + i));
throw new UncheckedIOException(e);
bytes += Math.max(n, 0);

Interactive Tools for This Topic

FAQ

How does the snippet fail?
The code throws `UncheckedIOException`. Handle it at the call site or let it propagate deliberately.
What does Selector Multiplexes Ready Channels print when run?
Execute the whole file; each printed line is prefixed with a label like `accepted =`.