Java NIO(New I/O,包含在 java.nio 包中,典型如 Channel + Buffer + Selector)本身不是线程安全的银弹,它只是提供了“非阻塞 + 多路复用”的能力。并发处理的关键在于如何组织线程模型和正确使用线程安全的组件。
下面从 核心模型 → 并发风险 → 常见并发方案 系统说明。
Selector(单线程)
├── Channel A
├── Channel B
└── Channel C
Selector 监听多个 Channel✅ 适合:
Boss Selector(Acceptor)
└── 接收连接
Worker Selector × N
├── Channel A
├── Channel B
acceptread / write / 业务✅ 适合:
Thread A → Channel A
Thread B → Channel B
❌ 不适合高并发
Selector 会出问题wakeup() 通知selector.wakeup(); // 安全跨线程唤醒
channel.register(selector, OP_READ);
ByteBuffer
ThreadLocal<ByteBuffer>channel.write(buffer);
OP_WRITE// I/O 线程
while (true) {
selector.select();
for (SelectionKey key : selector.selectedKeys()) {
if (key.isReadable()) {
ByteBuffer buf = ByteBuffer.allocate(1024);
SocketChannel sc = (SocketChannel) key.channel();
sc.read(buf);
executor.execute(() -> handle(buf));
}
}
}
✅ 优点:
EventLoopGroup (多个 EventLoop)
每个 EventLoop = 1 线程 + 1 Selector
Netty 已经帮你解决了:
EventLoopGroup boss = new NioEventLoopGroup(1);
EventLoopGroup worker = new NioEventLoopGroup();
Java NIO 本身不解决并发,它通过“单线程多路复用 + 线程隔离”来避免并发问题;真正的并发靠的是线程模型设计,而不是 NIO API。
如果你愿意,我可以:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。