---
title: "未关闭java.nio.channels.SocketChannel可导致Too many open files"
author: "DavisWang"
date: "2013-04-07T13:24:46Z"
tags: []
categories: ["编程语言"]
slug: "java-nio-channels-socketchannel-too-many-open-files"
draft: false
lastmod: "2013-04-07T13:26:48Z"
id: 1842521
url: "https://daviswang.iteye.com/blog/1842521"
---

在调用静态open方法创建java.nio.channels.SocketChannel对象后，必须调用close方法关闭SocketChannel对象以释放创建的文件句柄（fd）资源，否则如果不断地创建SocketChannel对象会使得打开文件的句柄数达到系统设定的上限，从而出现 “Too many open files”的问题。 现象：1）通过netstat -n | wc -l 查看连接数并不多; 2）系统或jvm报Too many open files; 3）通过命令ls -l /proc//fd | grep socket |wc -l 查看有大量与socket关联的文件句柄。 原因分析： 下面是java.nio.channels.SocketChannel的open方法，该方法调用SelectorProvider.provider().openSocketChannel()创建SocketChannel对象。 public static SocketChannel open() throws IOException { return SelectorProvider.provider().openSocketChannel(); } 我们先看SelectorProvider.provider()返回的对象。如果没有提供自定义的SelectorProvider实现，SelectorProvider.provider()会返回sun.nio.ch.DefaultSelectorProvider.create()创建的SelectorProvider对象，在linux下是sun.nio.ch.EPollSelectorProvider。 sun.nio.ch.EPollSelectorProvider的openSocketChannel()方法继承了sun.nio.ch.SelectorProviderImpl的实现，而sun.nio.ch.SelectorProviderImpl的openSocketChannel()直接返回创建的sun.nio.ch.SocketChannelImpl对象，其构造函数如下： SocketChannelImpl(SelectorProvider sp) throws IOException { super(sp); this.fd = Net.socket(true); this.fdVal = IOUtil.fdVal(fd); this.state = ST\_UNCONNECTED; } sun.nio.ch.Net.socket(boolean stream)的实现如下： static FileDescriptor socket(boolean stream) { return IOUtil.newFD(socket0(stream, false)); } IOUtil.newFD的实现如下 static FileDescriptor newFD(int i) { FileDescriptor fd = new FileDescriptor(); setfdVal(fd, i); return fd; } 可见，在创建SocketChannelImpl对象时创建了一个文件句柄，尽管这个文件句柄尚未和socket绑定，但已经开始占用系统的fd资源。所以在使用SocketChannel后一定要调用close()方法，尤其是在创建socket时出现异常时，一定要调用SocketChannel.close()方法将fd资源关闭/释放，否则就会出现上面的现象连接数不高，但文件句柄数很高。