JVM - java.lang.OutOfMemoryError: unable to create new native thread

来源:互联网 发布:淘宝卖的几百元智能机 编辑:程序博客网 时间:2024/05/29 16:35

问题描述

Java程序运行过程中抛出java.lang.OutOfMemoryError: unable to create new native thread,如下所示:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. java.lang.OutOfMemoryError: unable to create new native thread  
  2.     at java.lang.Thread.start0(Native Method)  
  3.     at java.lang.Thread.start(Thread.java:691)  
  4.     at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:949)  
  5.     at java.util.concurrent.ThreadPoolExecutor.processWorkerExit(ThreadPoolExecutor.java:1017)  
  6.     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1163)  
  7.     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)  
  8.     at java.lang.Thread.run(Thread.java:722)  

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Caused by: java.lang.OutOfMemoryError  
  2.     at java.util.zip.ZipFile.open(Native Method)  
  3.     at java.util.zip.ZipFile.<init>(ZipFile.java:214)  
  4.     at java.util.zip.ZipFile.<init>(ZipFile.java:144)  
  5.     at java.util.jar.JarFile.<init>(JarFile.java:153)  
  6.     at java.util.jar.JarFile.<init>(JarFile.java:117)  

从JVM层面去解决

减小thread stack的大小

JVM默认thread stack的大小为1024,这样当线程多时导致Native virtual memory被耗尽,实际上当thread stack的大小为128K 或 256K时是足够的,所以我们如果明确指定thread stack为128K 或 256K即可,具体使用-Xss,例如在JVM启动的JVM_OPT中添加如下配置

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. -Xss128k  

减小heap或permgen初始分配的大小

如果JVM启动的JVM_OPT中有如下配置

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. -Xms1303m -Xmx1303m -XX:PermSize=256m -XX:MaxPermSize=256m  
我们可以删除或减小初始化最小值的配置,如下

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. -Xms256m -Xmx1303m -XX:PermSize=64m -XX:MaxPermSize=256m  

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. -Xmx1303m -XX:MaxPermSize=256m  

升级JVM到最新的版本

最新版本的JVM一般在内存优化方面做的更好,升级JVM到最新的版本可能会缓解测问题

从操作系统层面去解决

使用64位操作系统

如果使用32位操作系统遇到unable to create new native thread,建议使用64位操作系统

增大OS对线程的限制

在Linux操作系统设定nofile和nproc,具体编辑/etc/security/limits.conf添加如下:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. soft    nofile          2048  
  2. hard    nofile          8192  

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. soft    nproc           2048  
  2. hard    nproc           8192  

如果使用Red Hat Enterprise Linux 6,编辑/etc/security/limits.d/90-nproc.conf,添加如下配置:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. # cat /etc/security/limits.d/90-nproc.conf  
  2. *          soft    nproc     1024  
  3. root       soft    nproc     unlimited  
  4.   
  5. user       -       nproc     2048 
0 0