OutOfMemoryError: unable to create new native thread

OutOfMemoryError: unable to create new native threadjava

这个错误是因为建立了太多的线程致使的。建立线程的数量能够由下面公式计算出来:segmentfault

(MaxProcessMemory - JVMMemory - ReservedOsMemory) / (ThreadStackSize) = Number of threads 

MaxProcessMemory:进程最大寻址空间。
JVMMMEMORY:jvm的内存空间(堆+永久区)-Xmx大小 (应该是实际分配大小)
ReservedOsMemory:操做系统预留内存
ThreadStackSize:-Xss大小

计算过程请参考:http://www.javashuo.com/article/p-wrvfheip-hc.htmlapp

重现该异常以下,jvm

import java.util.concurrent.CountDownLatch;

class TestThread extends Thread {


    CountDownLatch count = new CountDownLatch(1);

    public TestThread() {
        this.setDaemon(true);
    }

    /**
     * 线程一直等待
     */
    @Override
    public void run() {
        try {
            count.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

public class XssTest {
    public static void main(String args[]) {

        for (int i = 0; ; i++) {
            System.out.println("i = " + i);
            new Thread(new TestThread()).start();
        }
    }
}

运行结果:ide

i = 2027
Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
	at java.lang.Thread.start0(Native Method)
	at java.lang.Thread.start(Thread.java:714)
	at XssTest.main(XssTest.java:37)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:497)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

-Xss(ThreadStackSize)参数的做用

---the stack size for each threadui

JDK5.0之后每一个线程堆栈大小为1M,之前每一个线程堆栈大小为256K。在相同物理内存下,减少这个值能生成更多的线程。可是操做系统对一个进程内的线程数仍是有限制的,不能无限生成。this

使用不一样的Xss参数来运行下面这个程序,操作系统

public class XssDemo {

    private static int count = 0;

    public static void recursion() {
        //减小局部变量的声明,能够节省栈帧大小,增长调用深度
        long a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, q = 7, x = 8, y = 9, z = 10;
        count++;
        recursion();
    }

    public static void main(String args[]) {
        try {
            recursion();
        } catch (Throwable e) {
            System.out.println("deep of calling = " + count);
//            e.printStackTrace();
        }
    }
}

运行以下,线程

➜  helloworld java -Xmx128m -Xms128m -Xss1024k XssDemo
deep of calling = 12401
➜  helloworld java -Xmx128m -Xms128m -Xss512k XssDemo
deep of calling = 3524

当线程栈设置的较大时,栈的深度会比较大。code

-Xmx -Xms -Xss对线程建立数量的影响

参见http://jzhihui.iteye.com/blog/1271122

-Xms

intial java heap size

-Xmx

maximum java heap size

-Xss

the stack size for each thread

===========END===========

相关文章
相关标签/搜索