Too many open files,toomanyopenfiles


部署到linux下的tomcat,今天发现包了“java.net.SocketException: Too many open files”,以前从来没有遇到过,在此记录一下:

彻底解决问题的是第三步, 所以,可以直接跳到第三步去看解决方法和步骤,当日第一、第二步是我不断探索,尝试解决问题的过程,虽然没有找到点上,但是还是有些意义的,因为linux切实有打开资源数量的限制,肯定需要修改的。

异常信息:

Java代码  收藏代码
  1. ............  
  2. Oct 17, 2011 5:22:41 PM org.apache.tomcat.util.net.JIoEndpoint$Acceptor run  
  3. SEVERE: Socket accept failed  
  4. java.net.SocketException: Too many open files  
  5.         at java.net.PlainSocketImpl.socketAccept(Native Method)  
  6.         at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:375)  
  7.         at java.net.ServerSocket.implAccept(ServerSocket.java:470)  
  8.         at java.net.ServerSocket.accept(ServerSocket.java:438)  
  9.         at org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket(DefaultServerSocketFactory.java:59)  
  10.         at org.apache.tomcat.util.net.JIoEndpoint$Acceptor.run(JIoEndpoint.java:210)  
  11.         at java.lang.Thread.run(Thread.java:636)  
  12. Oct 17, 2011 5:22:43 PM org.apache.tomcat.util.net.JIoEndpoint$Acceptor run  
  13. SEVERE: Socket accept failed  
  14. java.net.SocketException: Too many open files  
  15.         at java.net.PlainSocketImpl.socketAccept(Native Method)  
  16.         at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:375)  
  17.         at java.net.ServerSocket.implAccept(ServerSocket.java:470)  
  18.         at java.net.ServerSocket.accept(ServerSocket.java:438)  
  19.         at org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket(DefaultServerSocketFactory.java:59)  
  20.         at org.apache.tomcat.util.net.JIoEndpoint$Acceptor.run(JIoEndpoint.java:210)  
  21.         at java.lang.Thread.run(Thread.java:636)  
  22. Oct 17, 2011 5:22:44 PM org.apache.tomcat.util.net.JIoEndpoint$Acceptor run  
  23. SEVERE: Socket accept failed  
  24. java.net.SocketException: Too many open files  
  25.         at java.net.PlainSocketImpl.socketAccept(Native Method)  
  26.         at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:375)  
  27.         at java.net.ServerSocket.implAccept(ServerSocket.java:470)  
  28.         at java.net.ServerSocket.accept(ServerSocket.java:438)  
  29.         at org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket(DefaultServerSocketFactory.java:59)  
  30.         at org.apache.tomcat.util.net.JIoEndpoint$Acceptor.run(JIoEndpoint.java:210)  
  31.         at java.lang.Thread.run(Thread.java:636)  
  32. ............  


原因:
   linux下有有文件限制,结果文件数操作最大限制,导致程序异常:问题是程序中有个静态方法打开文件时忘记关闭。两种解决方法,一是设置linux的最大文件打开数量(无法根本解决问题),二是解决程序中的bugs,即消除有问题的代码。

第一次解决
解决:
方法一、增大系统打开文件的数量(无法根本解决问题)、
   1、默认linux同时最大打开文件数量为1024个,用命令查看如下:ulimit -a:查看系统上受限资源的设置(open files (-n) 1024):

Java代码  收藏代码
  1. [root@**** bin]# ulimit -a  
  2. core file size          (blocks, -c) 0  
  3. data seg size           (kbytes, -d) unlimited  
  4. scheduling priority             (-e) 0  
  5. file size               (blocks, -f) unlimited  
  6. pending signals                 (-i) 16384  
  7. max locked memory       (kbytes, -l) 32  
  8. max memory size         (kbytes, -m) unlimited  
  9. open files                      (-n) 1024  
  10. pipe size            (512 bytes, -p) 8  
  11. POSIX message queues     (bytes, -q) 819200  
  12. real-time priority              (-r) 0  
  13. stack size              (kbytes, -s) 10240  
  14. cpu time               (seconds, -t) unlimited  
  15. max user processes              (-u) 16384  
  16. virtual memory          (kbytes, -v) unlimited  
  17. file locks                      (-x) unlimited  
  18. [root@**** bin]#  


2、可以修改同时打开文件的最大数基本可以解决:ulimit -n 4096

Java代码  收藏代码
  1. [root@**** bin]# ulimit -n 4096  
  2. [root@**** bin]# ulimit -a  
  3. core file size          (blocks, -c) 0  
  4. data seg size           (kbytes, -d) unlimited  
  5. scheduling priority             (-e) 0  
  6. file size               (blocks, -f) unlimited  
  7. pending signals                 (-i) 16384  
  8. max locked memory       (kbytes, -l) 32  
  9. max memory size         (kbytes, -m) unlimited  
  10. open files                      (-n) 4096  
  11. pipe size            (512 bytes, -p) 8  
  12. POSIX message queues     (bytes, -q) 819200  
  13. real-time priority              (-r) 0  
  14. stack size              (kbytes, -s) 10240  
  15. cpu time               (seconds, -t) unlimited  
  16. max user processes              (-u) 16384  
  17. virtual memory          (kbytes, -v) unlimited  
  18. file locks                      (-x) unlimited  
  19. [root@**** bin]#  


已经修改了最大打开文件数。

方法二、修改程序中的bugs:
程序中有个静态的方法打开文件后,没有关闭文件,导致每次请求都会去打开文件,在程序中填入关闭输入流的操作即可以:

Java代码  收藏代码
  1. public static List<GpsPoint> getArrayList() throws IOException {  
  2.   
  3.         List<GpsPoint> pointList = null;  
  4.         // 读取配置文件  
  5.         InputStream in = ParseGpsFile.class.getClassLoader().getResourceAsStream("GPS1.TXT");  
  6.           
  7.         // 读路径出错,换另一种方式读取配置文件  
  8.         if (null == in) {  
  9.               
  10.             System.out.println("读取文件失败");  
  11.               
  12.             return pointList;  
  13.         }  
  14.           
  15.         pointList = new ArrayList<GpsPoint>();  
  16.           
  17.         try {  
  18.             BufferedReader br = new BufferedReader(new InputStreamReader(in));  
  19.             String longtude = "";  
  20.             String latude = "";  
  21.             String elevation = "";  
  22.             while ((longtude = br.readLine()) != null) {  
  23.                   
  24.                 // 读下一行数据,读纬度  
  25.                 latude = br.readLine();  
  26.                   
  27.                 if (null == latude) {  
  28.                       
  29.                     // 退出循环  
  30.                     break;  
  31.                 }  
  32.                   
  33.                 // 读下一行数据,读海拔  
  34.                 elevation = br.readLine();  
  35.                 if (null == latude) {  
  36.                       
  37.                     // 退出循环  
  38.                     break;  
  39.                 }  
  40.                   
  41.                 // 加入一个点  
  42.                 pointList.add(gps2point(longtude, latude, elevation));  
  43.             }  
  44.               
  45.             in.close();  
  46.             System.out.println("\n\n");  
  47.         } catch (Exception e) {  
  48.               
  49.             in.close();  
  50.             e.printStackTrace();  
  51.         }  
  52.           
  53.         return pointList;  
  54.     }  



问题彻底解决

-----
第二次解决:
实际测试后发现这个问题还没有解决,最终又找了些方法,经过一段时间的测试,似乎解决了问题:

具体步骤如下:
linux为redhat服务器版本(非个人版),必须设置的内容:

1、/etc/pam.d/login 添加

Java代码  收藏代码
  1. session required     /lib/security/pam_limits.so  


# 注意看这个文件的注释
具体文件的内容为:

Java代码  收藏代码
  1. [root@**** ~]# vi /etc/pam.d/login  
  2. #%PAM-1.0  
  3. auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so  
  4. auth       include      system-auth  
  5. account    required     pam_nologin.so  
  6. account    include      system-auth  
  7. password   include      system-auth  
  8. # pam_selinux.so close should be the first session rule  
  9. session    required     pam_selinux.so close  
  10. session    optional     pam_keyinit.so force revoke  
  11. session    required     pam_loginuid.so  
  12. session    include      system-auth  
  13. session    optional     pam_console.so  
  14. # pam_selinux.so open should only be followed by sessions to be executed in the user context  
  15. session    required     pam_selinux.so open  
  16.   
  17. ~  
  18. "/etc/pam.d/login" 15L, 644C  


修改后的内容:

Java代码  收藏代码
  1. -bash: [root@****: command not found  
  2. [root@**** ~]# clear  
  3. [root@**** ~]# cat /etc/pam.d/login  
  4. #%PAM-1.0  
  5. auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so  
  6. auth       include      system-auth  
  7. account    required     pam_nologin.so  
  8. account    include      system-auth  
  9. password   include      system-auth  
  10. # pam_selinux.so close should be the first session rule  
  11. session    required     pam_selinux.so close  
  12. session    optional     pam_keyinit.so force revoke  
  13. session    required     pam_loginuid.so  
  14. session    include      system-auth  
  15. session    optional     pam_console.so  
  16. # pam_selinux.so open should only be followed by sessions to be executed in the user context  
  17. session    required     pam_selinux.so open  
  18. # kevin.xie added, fixed 'too many open file' bug, limit open max files 1024, 2011-10-24  
  19. session required     /lib/security/pam_limits.so  
  20.   
  21. [root@**** ~]#  


2. /etc/security/limits.conf 添加

Java代码  收藏代码
  1. root          –    nofile       1006154  


root 是一个用户,如果是想所有用户生效的话换成 * ,设置的数值与硬件配置有关,别设置太大了。
修改前内容

Java代码  收藏代码
  1. [root@**** ~]# cat /etc/security/limits.conf  
  2. # /etc/security/limits.conf  
  3. #  
  4. #Each line describes a limit for a user in the form:  
  5. #  
  6. #<domain>        <type>  <item>  <value>  
  7. #  
  8. #Where:  
  9. #<domain> can be:  
  10. #        - an user name  
  11. #        - a group name, with @group syntax  
  12. #        - the wildcard *, for default entry  
  13. #        - the wildcard %, can be also used with %group syntax,  
  14. #                 for maxlogin limit  
  15. #  
  16. #<type> can have the two values:  
  17. #        - "soft" for enforcing the soft limits  
  18. #        - "hard" for enforcing hard limits  
  19. #  
  20. #<item> can be one of the following:  
  21. #        - core - limits the core file size (KB)  
  22. #        - data - max data size (KB)  
  23. #        - fsize - maximum filesize (KB)  
  24. #        - memlock - max locked-in-memory address space (KB)  
  25. #        - nofile - max number of open files  
  26. #        - rss - max resident set size (KB)  
  27. #        - stack - max stack size (KB)  
  28. #        - cpu - max CPU time (MIN)  
  29. #        - nproc - max number of processes  
  30. #        - as - address space limit  
  31. #        - maxlogins - max number of logins for this user  
  32. #        - maxsyslogins - max number of logins on the system  
  33. #        - priority - the priority to run user process with  
  34. #        - locks - max number of file locks the user can hold  
  35. #        - sigpending - max number of pending signals  
  36. #        - msgqueue - max memory used by POSIX message queues (bytes)  
  37. #        - nice - max nice priority allowed to raise to  
  38. #        - rtprio - max realtime priority  
  39. #  
  40. #<domain>      <type>  <item>         <value>  
  41. #  
  42.   
  43. #*               soft    core            0  
  44. #*               hard    rss             10000  
  45. #@student        hard    nproc           20  
  46. #@faculty        soft    nproc           20  
  47. #@faculty        hard    nproc           50  
  48. #ftp             hard    nproc           0  
  49. #@student        -       maxlogins       4  
  50.   
  51. # End of file  
  52. [root@**** ~]#  
  53. [root@**** ~]# cat /etc/security/limits.conf  
  54. # /etc/security/limits.conf  
  55. #  
  56. #Each line describes a limit for a user in the form:  
  57. #  
  58. #<domain>        <type>  <item>  <value>  
  59. #  
  60. #Where:  
  61. #<domain> can be:  
  62. #        - an user name  
  63. #        - a group name, with @group syntax  
  64. #        - the wildcard *, for default entry  
  65. #        - the wildcard %, can be also used with %group syntax,  
  66. #                 for maxlogin limit  
  67. #  
  68. #<type> can have the two values:  
  69. #        - "soft" for enforcing the soft limits  
  70. #        - "hard" for enforcing hard limits  
  71. #  
  72. #<item> can be one of the following:  
  73. #        - core - limits the core file size (KB)  
  74. #        - data - max data size (KB)  
  75. #        - fsize - maximum filesize (KB)  
  76. #        - memlock - max locked-in-memory address space (KB)  
  77. #        - nofile - max number of open files  
  78. #        - rss - max resident set size (KB)  
  79. #        - stack - max stack size (KB)  
  80. #        - cpu - max CPU time (MIN)  
  81. #        - nproc - max number of processes  
  82. #        - as - address space limit  
  83. #        - maxlogins - max number of logins for this user  
  84. #        - maxsyslogins - max number of logins on the system  
  85. #        - priority - the priority to run user process with  
  86. #        - locks - max number of file locks the user can hold  
  87. #        - sigpending - max number of pending signals  
  88. #        - msgqueue - max memory used by POSIX message queues (bytes)  
  89. #        - nice - max nice priority allowed to raise to  
  90. #        - rtprio - max realtime priority  
  91. #  
  92. #<domain>      <type>  <item>         <value>  
  93. #  
  94.   
  95. #*               soft    core            0  
  96. #*               hard    rss             10000  
  97. #@student        hard    nproc           20  
  98. #@faculty        soft    nproc           20  
  99. #@faculty        hard    nproc           50  
  100. #ftp             hard    nproc           0  
  101. #@student        -       maxlogins       4  
  102. # kevin.xie added, fixed 'too many open file' bug, limit open max files 1024, 2011-10-24  
  103. * - nofile 102400  
  104.   
  105. # End of file  
  106. [root@**** ~]#  


修改后的内容

Java代码  收藏代码
  1.   



3. 修改 /etc/rc.local   添加

Java代码  收藏代码
  1. echo 8061540 > /proc/sys/fs/file-max  


修改前内容

Java代码  收藏代码
  1. [root@**** ~]# cat /proc/sys/fs/file-max  
  2. 4096  
  3. [root@**** ~]#  


修改后内容

Java代码  收藏代码
  1. [root@**** ~]# cat /proc/sys/fs/file-max  
  2. 4096000  
  3. [root@**** ~]#  


做完3个步骤,就可以了。


**************************************
补充说明:
/proc/sys/fs/file-max
该文件指定了可以分配的文件句柄的最大数目。如果用户得到的错误消息声明由于打开文件数已经达到了最大值,从而他们不能打开更多文件,则可能需要增加该值。可将这个值设置成有任意多个文件,并且能通过将一个新数字值写入该文件来更改该值。
缺省设置:4096
/proc/sys/fs/file-nr
该文件与 file-max 相关,它有三个值:
已分配文件句柄的数目
已使用文件句柄的数目
文件句柄的最大数目
该文件是只读的,仅用于显示信息。
关于“打开文件数”限制
Linux系统上对每一个用户可使用的系统资源都是有限制的,这是多用户系统必然要采用的一种资源管理手段,试想假如没有这种机制,那么任何一个普通用户写一个死循环程序,用不了多久系统就要“拒绝服务”了。
今天我遇到了tomcat日志报的错误信息”too many open files”,第一意识就想到了是ulimit控制的”open files“限制。然而问题来了。我在/etc/profile里加入了 ulimit -n 4096保存之后,普通用户登录的时候均会收到一条错误信息ulimit: open files: cannot modify limit: Operation not permitted。然后普通用户的open files限制还是默认值1024。
然后开始在互联网上搜索关于ulimit的信息。互联网果然方便,信息铺天盖地。大家也可以搜一下试一下。其中我了解到两个以前不知道的相关内容。
第一个是内核参数 fs.file-max  ,影射为 /proc/sys/fs/file-max
第二个是配置文件 /etc/security/limits.conf
其中大部分的信息中提到 将 /proc/sys/fs/file-max的值设置为4096和ulimit -n 4096是相同的效果。对此我很怀疑,为什么呢?首先ulimit 是一个普通用户也可以使用的命令,而fs.file-max只有root有权设置。其次,很明显fs.file-max是一个全局的设置,而ulimit 是一个局部的设置,很明显的是不相同的。
带着疑虑,又在网上搜索了许久,未果(实际上是我搜索的关键字不够准确)。
最后终于在内核文档/usr/src/linux/Documentation/sysctl/fs.txt里找到下面一段话:
file-max & file-nr:
The kernel allocates file handles dynamically, but as yet it doesn’t free them again. The value in file-max denotes the maximum number of file-handles that the Linux kernel will allocate. When you get lots of error messages about running out of file handles, you might want to increase this limit.
The three values in file-nr denote the number of allocated file handles, the number of unused file handles and the maximum number of file handles. When the allocated file handles come close to the maximum, but the number of unused file handles is significantly greater than 0, you’ve encountered a peak in your usage of file handles and you don’t need to increase the maximum.
这两段话的大致意思是:
内核动态地分配和释放“file handles”(句柄)。file-max的值是内核所能分配到的最大句柄数。当你收到大量关于句柄用完的错误信息时,你可以需要增加这个值以打破老的限制。
file-nr中的三个值的含意分别是:系统已经分配出去(正在使用)的句柄数,没有用到的句柄数和所有分配到的最大句柄数。当分配出去的句柄数 接近 最大句柄数,而“无用的句柄数”大于零时,表明你遇到了一个“句柄”使用高峰,这意为着你不需要增加file-max的值。
看完这段话,相信大家都明白了。file-max是系统全局的可用句柄数。根据我后来又翻查的信息,以及对多个系统的查看求证,这个参数的默认值是跟内存大小有关系的,增加物理内存以后重启机器,这个值会增大。大约1G内存10万个句柄的线性关系。
再回过头来看这两段话,不知道你意识到了没有,文中只提到了file-max的增加,而没有提到了该值的减少。那些在操作ulimit时同时操 作了file-max的哥们儿,估计无一例外地将file-max设置成了4096或者2048。但以似乎也没有因此而导致系统无法打开文件或者建议连 接。(实际上,我将file-max的值设备成256,然后使用shell编写用vi打开500个文件角本运行,并没有得到任何错误信息,查看file- nr的值,系统当前分配的句柄值已经远超过了后面的最大值。所以我猜想对于file-max的任何减少的操作都是毫无意义的,姑且不去管他。实践中需要减 少file-max的时候总是不多见的。 )实事证明我犯了一个致命的错误。我测试的时候使用的是root用户,而当我再次使用普通用户测试的时候,预料中的错误信息出现了:”Too many open files in system”。可见,file-max的减少对系统也是影响力的。前面的结论“所以我猜想对于file-max的任何减少的操作都是毫无意义的”是错误 的。
然后便是/etc/security/limits.conf文件,这个文件很简单,一看就能明白。
于是我按照注释中描述的格式两个两行:
*  soft  nofile  4096
*  hard  nofile  4096
恐怖的是,网上居然有人说改了这个设置是需要重启系统的!实在是让人想不通啊,鼎鼎大名的UNIX系统,怎么可能因为这么小小的一个改动就需要 重启系统呢?结果当我再次以普通用户登录的时候,那个”ulimit: open files: cannot modify limit: Operation not permitted”提示没有了,查看ulimit -n,果然已经变成了4096。
linux lsof 修改句柄限制(转)
在Linux下,我们使用ulimit -n 命令可以看到单个进程能够打开的最大文件句柄数量(socket连接也算在里面)。系统默认值1024。
对于一般的应用来说(象Apache、系统进程)1024完全足够使用。但是如何象squid、mysql、java等单进程处理大量请求的应用 来说就有点捉襟见肘了。如果单个进程打开的文件句柄数量超过了系统定义的值,就会提到“too many files open”的错误提示。如何知道当前进程打开了多少个文件句柄呢?下面一段小脚本可以帮你查看:
lsof -n |awk ‘{print $2}’|sort|uniq -c |sort -nr|more
在系统访问高峰时间以root用户执行上面的脚本,可能出现的结果如下:
# lsof -n|awk ‘{print $2}’|sort|uniq -c |sort -nr|more
131 24204
57 24244
57 24231
56 24264
其中第一行是打开的文件句柄数量,第二行是进程号。得到进程号后,我们可以通过ps命令得到进程的详细内容。
ps -aef|grep 24204
mysql 24204 24162 99 16:15 ? 00:24:25 /usr/sbin/mysqld
哦,原来是mysql进程打开最多文件句柄数量。但是他目前只打开了131个文件句柄数量,远远底于系统默认值1024。
但是如果系统并发特别大,尤其是squid服务器,很有可能会超过1024。这时候就必须要调整系统参数,以适应应用变化。Linux有硬性限制和软性限制。可以通过ulimit来设定这两个参数。方法如下,以root用户运行以下命令:
ulimit -HSn 4096
以上命令中,H指定了硬性大小,S指定了软性大小,n表示设定单个进程最大的打开文件句柄数量。个人觉得最好不要超过4096,毕竟打开的文件句 柄数越多响应时间肯定会越慢。设定句柄数量后,系统重启后,又会恢复默认值。如果想永久保存下来,可以修改.bash_profile文件,可以修改 /etc/profile 把上面命令加到最后。



仍未处理的问题:
为什么redhat9的个人版按照以上的方式修改1024tcp连接限制依然不行呢?
是因为个人版最多支持1024个tcp连接,还是修改方式、相关文件会有所不同?

以上内容,来源网络并加自己亲自测试,经过测试,似乎没有再出现过问题,但不知道是否真的解决,有待更长时间的测试看看

第三次解决--还解决不了,就彻底无语了(经过压力测试,运行7天再也没有出现该问题)
问题的原因是:原来的MINA2程序之关了IoSession,并没有关闭IoConnector实例,但恰恰就是因为没有关闭每次打开的IoConnector实例,造成了"Too many open files ".
原来的程序:

Java代码  收藏代码
  1. /**  
  2.      * <pre><b>功能描述:</b>获取异步的session实例。  
  3.      *   
  4.      * @author :Kevin.xie  
  5.      * <b>创建日期 :</b>2011-9-15 上午10:06:27  
  6.      *  
  7.      * @return  
  8.      *  
  9.      * <b>修改历史:</b>(修改人,修改时间,修改原因/内容)  
  10.      *  
  11.      * </pre>  
  12.      */    
  13.     public static IoSession getSession1() {    
  14.     
  15.         // 创建客户端连接器    
  16.         IoConnector connector = new NioSocketConnector();    
  17.         // 设置事件处理器    
  18.         connector.setHandler(new WebClientHandler());    
  19.         // 设置编码过滤器和按行读取数据模式    
  20.         connector.getFilterChain()    
  21.                 .addLast("codec", new ProtocolCodecFilter(new ObdDemuxingProtocolCodecFactory(false)));    
  22.         // 创建连接    
  23.         ConnectFuture future = connector.connect(new InetSocketAddress(ServerConfigBoundle.getServerIp(),    
  24.                 ServerConfigBoundle.getServerPort()));    
  25.         // 等待连接创建完成    
  26.         future.awaitUninterruptibly();    
  27.         // 获取连接会话    
  28.         IoSession session = future.getSession();    
  29.             
  30.         return session;    
  31.     }    
  32.     
  33.    /**  
  34.      * <pre><b>功能描述:</b>必须要关闭Connector和IoSession  
  35.      * @author :Kevin.xie  
  36.      * <b>创建日期 :</b>2011-10-20 上午10:20:54  
  37.      *  
  38.      * @param session 要关闭的session  
  39.      *  
  40.      * <b>修改历史:</b>(修改人,修改时间,修改原因/内容)  
  41.      *  
  42.      * </pre>  
  43.      */    
  44.     public static void closeSession(IoSession session) {    
  45.     
  46.         if (session != null && !session.isClosing()) {    
  47.                 
  48.             // 没有关闭,就关闭    
  49.             session.close(true);    
  50.             session = null;    
  51.         }    
  52.     }   


修改后的程序

Java代码  收藏代码
  1. /**  
  2.      *   
  3.      * <pre><b>功能描述:</b>获取IoConnector和异步的session实例  
  4.      * 无法关闭。特别的提醒,NioSocketConnector 也要关闭。  
  5.      * 函数名是 dispose()。这点特别重要。这次出现 too many open files 的问题根源在这里  
  6.      *   
  7.      * @author :Kevin.xie  
  8.      * <b>创建日期 :</b>2011-9-15 上午10:06:27  
  9.      *  
  10.      * @return  
  11.      *  
  12.      * <b>修改历史:</b>(修改人,修改时间,修改原因/内容)  
  13.      *  
  14.      * </pre>  
  15.      */    
  16.     public static Map<String, Object> getConnectorAndSession() {    
  17.     
  18.         // 创建客户端连接器    
  19.         IoConnector connector = new NioSocketConnector();    
  20.         // 设置事件处理器    
  21.         connector.setHandler(new WebClientHandler());    
  22.         // 设置编码过滤器和按行读取数据模式    
  23.         connector.getFilterChain()    
  24.                 .addLast("codec", new ProtocolCodecFilter(new ObdDemuxingProtocolCodecFactory(false)));    
  25.         // 创建连接    
  26.         ConnectFuture future = connector.connect(new InetSocketAddress(ServerConfigBoundle.getServerIp(),    
  27.                 ServerConfigBoundle.getServerPort()));    
  28.         // 等待连接创建完成    
  29.         future.awaitUninterruptibly();    
  30.         // 获取连接会话    
  31.         IoSession session = future.getSession();    
  32.             
  33.         Map<String, Object> map = new HashMap<String, Object>();    
  34.         map.put(CONNECTOR_KEY, connector);    
  35.         map.put(SESSION_KEY, session);    
  36.             
  37.         return map;    
  38.     }    
  39.     
  40. /**  
  41.      *   
  42.      * <pre><b>功能描述:</b>必须要关闭Connector和IoSession  
  43.      * 特别的提醒,NioSocketConnector 也要关闭。  
  44.      * 函数名是 dispose()。这点特别重要。这次出现 too many open files 的问题根源在这里  
  45.      * @author :Kevin.xie  
  46.      * <b>创建日期 :</b>2011-10-20 上午10:20:54  
  47.      *  
  48.      * @param connector 要关闭的IoConnector,不关闭会报 too many open files 错误  
  49.      * @param session 要关闭的session  
  50.      *  
  51.      * <b>修改历史:</b>(修改人,修改时间,修改原因/内容)  
  52.      *  
  53.      * </pre>  
  54.      */    
  55.     public static void closeConnectorAndSession(IoConnector connector, IoSession session) {    
  56.     
  57.         if (session != null && !session.isClosing()) {    
  58.                 
  59.             // 没有关闭,就关闭    
  60.             session.close(true);    
  61.             session = null;    
  62.         }    
  63.             
  64.         if (connector != null && !(connector.isDisposing() || connector.isDisposed())) {    
  65.                 
  66.             // 没有关闭,就关闭    
  67.             connector.dispose();    
  68.             connector = null;    
  69.         }    
  70.     }    
  71. ]    



用完后一定要释放资源:

Java代码  收藏代码
  1.  Map<String, Object> resultMap = SocketUtils.getConnectorAndSession();  
  2.   IoSession session = (IoSession) resultMap.get(SocketUtils.SESSION_KEY);  
  3.   IoConnector connector = (IoConnector) resultMap.get(SocketUtils.CONNECTOR_KEY);  
  4. ............  
  5. ............          
  6.   
  7.   // 主动关闭连接  
  8.   SocketUtils.closeConnectorAndSession(connector, session);  



同时在配置文件 /etc/security/limits.conf  加了一个配置(该不该问题不大):
# kevin.xie added, fixed 'too many open file' bug', 2012-01-04
* soft nofile 65536
* hard nofile 65536

Java代码  收藏代码
    1. # 第二次解决添加的内容    
    2. # kevin.xie added, fixed 'too many open file' bug, limit open max files 1024, 2011-10-24    
    3. * - nofile 102400    
    4.     
    5. # 第三次(本次)解决添加的问题(不过这个应该可以不修改,没有印证,也懒得修改了)    
    6. # kevin.xie added, fixed 'too many open file' bug', 2012-01-04    
    7. * soft nofile 65536    
    8. * hard nofile 65536   
    9. 原帖子出自--http://xieyanhua.iteye.com/blog/1198708

相关内容