在 java nio 中,调用 selector 的 close() 方法会关闭该选择器并释放所有相关的系统资源。执行此操作后,选择器将不再处于打开状态,任何试图在其上注册新通道或查询已选键的操作都会抛出 closedselectorexception。此外,该方法还会自动取消所有已注册的 selectionkey,但不会关闭这些键所关联的 channel 对象本身。

如何正确关闭 Selector 以释放资源
要正确关闭 Selector,只需直接调用其 close() 方法即可。由于 Selector 实现了 AutoCloseable 接口,推荐使用 try-with-resources 语句来确保资源被自动释放。关闭后,所有与该选择器关联的 SelectionKey 都会被标记为无效(cancelled),但底层的 SocketChannel 或 ServerSocketChannel 仍然保持打开状态,需要单独关闭以避免资源泄漏。

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Set;
public class SelectorCloseExample {
public static void main(String[] args) throws IOException {
// 使用 try-with-resources 自动关闭 Selector
try (Selector selector = Selector.open();
ServerSocketChannel serverChannel = ServerSocketChannel.open()) {
serverChannel.configureBlocking(false);
serverChannel.bind(new InetSocketAddress(8080));
// 注册通道到选择器
SelectionKey key = serverChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Selector is open: " + !selector.isOpen());
// 手动触发关闭逻辑(try-with-resources 会自动处理)
// selector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
关闭 Selector 对已注册 Key 的影响
当 Selector 被关闭时,它内部维护的所有 SelectionKey 集合会被清空,每个键的状态都会变为 CANCELLED。这意味着之前通过 key.isValid() 检查为 true 的键,在关闭后会立即变为 false。开发者需要注意,虽然键被取消了,但关联的通道并未关闭,如果后续代码尝试访问这些键或通道,可能会遇到异常或需要重新注册。
在代码库出现结构漂移之前,扫描JS或TS代码库中的禁止导入、循环依赖、孤立模块和其他依赖规则违规情况。

import java.io.IOException;
import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.net.InetSocketAddress;
public class SelectorKeyStateCheck {
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
ServerSocketChannel channel = ServerSocketChannel.open();
channel.configureBlocking(false);
channel.bind(new InetSocketAddress(9090));
SelectionKey key = channel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Before close - Key valid: " + key.isValid());
System.out.println("Before close - Selector open: " + selector.isOpen());
// 关闭 Selector
selector.close();
System.out.println("After close - Key valid: " + key.isValid());
System.out.println("After close - Selector open: " + selector.isOpen());
// 注意:channel 仍然有效,可以单独关闭
channel.close();
}
}
关闭 Selector 后尝试再次注册会发生什么
如果在 Selector 关闭后尝试向其注册新的 Channel,或者查询已选中的键集,Java NIO 会抛出 java.nio.channels.ClosedSelectorException。这是一个运行时异常,表明选择器已经不可用。因此,在编写网络服务器逻辑时,必须确保在关闭选择器后不再进行任何注册或轮询操作,否则程序会崩溃。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










