Java NIO 中网络编程怎么优雅关闭
在 java nio 中,优雅关闭的核心是确保 selector、channel 和 socket 资源被正确释放,同时避免线程阻塞或数据丢失。具体做法是先调用 selector.wakeup() 唤醒阻塞的 select() 操作,再遍历并关闭所有已注册的 selectionkey 对应的 socketchannel,最后关闭 selector 本身。这样做可以防止资源泄漏,并确保客户端连接被正常终止。

如何避免 Selector 关闭时的异常
关闭 Selector 时,如果仍有线程在 select() 中阻塞,会抛出 ClosedSelectorException。解决方法是在关闭前调用 wakeup(),并捕获该异常以安全退出循环。此外,需确保所有 Channel 已关闭,否则可能引发 IOException。

使用 Husky 将 pre-commit、pre-push 和 commit-msg 检查集成到仓库中,以便代理和开发人员在更改离开工作站之前运行相同的本地防护措施。
import java.io.IOException;
import java.net.InetSocketAddress;
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 GracefulShutdownExample {
private Selector selector;
private ServerSocketChannel serverChannel;
public void start() throws IOException {
selector = Selector.open();
serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.bind(new InetSocketAddress(8080));
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
while (!Thread.currentThread().isInterrupted()) {
try {
int readyChannels = selector.select();
if (readyChannels == 0) continue;
Iterator<selectionkey> keys = selector.selectedKeys().iterator();
while (keys.hasNext()) {
SelectionKey key = keys.next();
keys.remove();
if (key.isAcceptable()) {
handleAccept(key);
}
}
} catch (IOException e) {
// 处理异常,如 ClosedSelectorException
break;
}
}
}
private void handleAccept(SelectionKey key) throws IOException {
SocketChannel client = serverChannel.accept();
if (client != null) {
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
}
}
public void shutdown() {
try {
selector.wakeup(); // 唤醒 select()
for (SelectionKey key : selector.keys()) {
key.cancel();
if (key.channel() instanceof SocketChannel) {
((SocketChannel) key.channel()).close();
}
}
selector.close();
serverChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
GracefulShutdownExample example = new GracefulShutdownExample();
example.start();
// 模拟外部触发关闭
Thread shutdownThread = new Thread(() -> {
try { Thread.sleep(5000); } catch (InterruptedException e) {}
example.shutdown();
});
shutdownThread.start();
}
}</selectionkey>
基于程序中某个输入、条件或结果的具体问题
当 Selector 关闭时,若未先调用 wakeup(),阻塞的 select() 会抛出 ClosedSelectorException。上述代码通过先 wakeup() 再关闭资源,避免了此异常。实际运行中,shutdown() 方法会立即中断 select() 循环,确保程序平稳退出。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










