`
lzj0470
  • 浏览: 1245180 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

java.net.SocketException: Too many open files 问题的解决办法

阅读更多
linux 上tomcat 服务器抛出socket异常“文件打开太多”的问题
java.net.SocketException: Too many open files
at java.net.PlainSocketImpl.socketAccept(Native Method)
at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:384)
at java.net.ServerSocket.implAccept(ServerSocket.java:450)
at java.net.ServerSocket.accept(ServerSocket.java:421)
at org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket(DefaultServerSocketFactory.java:60)
at org.apache.tomcat.util.net.PoolTcpEndpoint.acceptSocket(PoolTcpEndpoint.java:407)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:70)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:595)


该问题的根本原因是由于系统文件资源的限制导致的。

[root@test security]# ulimit -a
core file size        (blocks, -c) 0
data seg size         (kbytes, -d) unlimited
file size             (blocks, -f) unlimited
max locked memory     (kbytes, -l) unlimited
max memory size       (kbytes, -m) unlimited
open files                    (-n) 1024
pipe size          (512 bytes, -p) 8
stack size            (kbytes, -s) 8192
cpu time             (seconds, -t) unlimited
max user processes            (-u) 7168
virtual memory        (kbytes, -v) unlimited


通过以上命令,我们可以看到open files 的最大数为1024
那么我们可以通过一下命令修改该参数的最大值
2. ulimit -n 4096
[root@test security]# ulimit -n 4096

用ulimit -n 修改open files 总是不能保持。所以用下面一个简单的办法更好些。

修改/etc/security/limits.conf 添加如下一行:

* - nofile 1006154

修改/etc/pam.d/login添加如下一行

session required /lib/security/pam_limits.so

这次永久修改后程序就再没那个问题了,一直稳定运行。

上面的办法只是临时解决办法,问题还是要从根本上解决,于是把以前的代码由认真地看了一遍。终于找到了,罪魁祸首。

在读取文件时,有一些使用的BufferedReader 没有关闭。导致文件一直处于打开状态。造成资源的严重浪费。

修改之后的简单代码如下:

public void test(){
    BufferedReader reader =null;
    try{
        reader = 读取文件;
        String line = "";
        while( ( ine=reader.readLine())!=null){
           其他操作
        }

    } catch (IOException e){
        System.out.println(e);
    } finally{  
         if(reader !=null){
                try {
                    reader.close();
                } catch (IOException e) {
                      e.printStackTrace();
                }
          }
    }

}


分享到:
评论
2 楼 lzj0470 2011-12-22  
netkiller.github.com 写道
运行即可


cat >> /etc/security/limits.conf <<EOF
root soft nofile 10240
root hard nofile 65536
nobody soft nofile 10240
nobody hard nofile 65536
EOF

谢谢
1 楼 netkiller.github.com 2011-12-21  
运行即可


cat >> /etc/security/limits.conf <<EOF
root soft nofile 10240
root hard nofile 65536
nobody soft nofile 10240
nobody hard nofile 65536
EOF

相关推荐

Global site tag (gtag.js) - Google Analytics