← 中文资源

简体中文版本

Selector 单线程多路复用

一个 Selector 单线程监听 accept 与多个连接的读就绪事件:注册 OP_ACCEPT/OP_READ,手动 remove selectedKeys,读到 EOF 就关闭通道,避免每连接一个线程。

阅读英文原文

实现说明

逻辑集中在类 SelectorMultiplexer和函数 probe里。 驱动整个流程的是 for (int i = 1; i <= 2; i++) 这一个循环。资源写在 try 头部,关闭由编译器生成、异常安全。代码拒绝在坏状态上继续,在守卫处直接抛出 UncheckedIOException。

使用要点

  • 演示输出是带标签的(accepted =),每个操作都会留下自己的一行标注。
  • 运行整个文件:main 会依次驱动 probe。

常见问题

这个示例会以什么方式失败?

代码会抛出 UncheckedIOException。请在调用点处理,或有意让它向上传播。

运行「Selector 单线程多路复用」会打印什么?

整个文件跑完,输出行以 accepted = 这类前缀开头。

主签名形如 private static void probe(InetSocketAddress address, String message)

核心语句

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

代码示例

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);
        }
    }
}