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

曾常常遇到此问题,一般想法就是改动配置启动參数,想方设法增大參数,觉得这样能够避免内存溢出。但效果基本上还是会出错。我在网上找到了一篇文章解决此问题 点击打开链接 主要观点为

这个异常问题本质原因是我们创建了太多的线程,而能创建的线程数是有限制的,导致了异常的发生。能创建的线程数的详细计算公式例如以下:
(MaxProcessMemory - JVMMemory - ReservedOsMemory) / (ThreadStackSize) = Number of threads
MaxProcessMemory 指的是一个进程的最大内存
JVMMemory         JVM内存
ReservedOsMemory  保留的操作系统内存
ThreadStackSize      线程栈的大小

在java语言里, 当你创建一个线程的时候,虚拟机会在JVM内存创建一个Thread对象同一时候创建一个操作系统线程,而这个系统线程的内存用的不是JVMMemory,而是系统中剩下
的内存(MaxProcessMemory - JVMMemory - ReservedOsMemory)。 

由公式得出结论:你给JVM内存越多,那么你能创建的线程越少,越easy发生java.lang.OutOfMemoryError: unable to create new native thread。 

解决这个问题:
1, 假设程序中有bug,导致创建大量不须要的线程或者线程没有及时回收,那么必须解决这个bug,改动參数是不能解决这个问题的。
2, 假设程序确实须要大量的线程,现有的设置不能达到要求,那么能够通过改动MaxProcessMemory,JVMMemory,ThreadStackSize这三个因素,来添加能创建的线程数:
a, MaxProcessMemory 使用64位操作系统
b, JVMMemory   降低JVMMemory的分配
c, ThreadStackSize  减小单个线程的栈大小

这个观点让我開始也非常不解,但细致查看了一下出错日志

# There is insufficient memory for the Java Runtime Environment to continue.
# Native memory allocation (malloc) failed to allocate 2334888 bytes for Chunk::new
# An error report file with more information is saved as:
# D:\xxx_err_pid1904.log
在查看具体的pid日志,则惊喜的发现其给出的解决方法与上面讲到的理论同样

#
# There is insufficient memory for the Java Runtime Environment to continue.
# Native memory allocation (malloc) failed to allocate 2355528 bytes for Chunk::new
# Possible reasons:
#   The system is out of physical RAM or swap space
#   In 32 bit mode, the process size limit was hit
# Possible solutions:
#   Reduce memory load on the system
#   Increase physical memory or swap space
#   Check if swap backing store is full
#   Use 64 bit Java on a 64 bit OS
#   <span style="color:#FF0000;">Decrease Java heap size (-Xmx/-Xms)</span>
#   <span style="color:#FF0000;">Decrease number of Java threads</span>
#   <span style="color:#FF0000;">Decrease Java thread stack sizes (-Xss)</span>
#   Set larger code cache with -XX:ReservedCodeCacheSize=
# This output file may be truncated or incomplete.
#
#  Out of Memory Error (allocation.cpp:328), pid=4308, tid=6720
#
# JRE version: 7.0_25-b16
# Java VM: Java HotSpot(TM) Server VM (23.25-b01 mixed mode windows-x86 )
# Failed to write core dump. Call to MiniDumpWriteDump() failed
#
注意上面标红色处
于是将tomcat服务启动參数都改小了一半,变为例如以下參数

-Xms256M
-Xmx512M
-Xss1M

再启动服务,并马上观察任务管理中tomcat进程具体,内存使用情况较出错时内存使用上涨的最大值小了,并逐渐回落到一个比較低的值。而CPU的使用情况在刚启动时比出错时值要高一点,启动后回归正常。而且服务能够正常启动了。

综合上面的情况,并在简单的实践后,我觉得引用文章中的理论应该是有道理的,所下面次再遇到此异常,最好还是试试将有关配置參数减少,没准会解决这个问题。

posted @ 2015-05-17 13:27  hrhguanli  阅读(20892)  评论(0编辑  收藏  举报