Welcome everyone

Unable to create new native thread

java 汪明鑫 509浏览 0评论

Exception in thread “main” java.lang.OutOfMemoryError: unable to create new native thread

无意间遇到过这样的异常

意思是没法创建新的线程,线程肯定需要空间存储,但是线程的空间占用并不是Jvm本身内存空间

 

线程可以使用的空间:

MaxProcessMemory – JVMMemory – ReservedOsMemory

MaxProcessMemory 指的是一个进程的最大内存

JVMMemory JVM内存

ReservedOsMemory 保留的操作系统内存

 

线程数:

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

 

 

因为我们Jvm使用太大内存或者创建的线程太多都可能触发上面的异常

举个简单的demo:

/**
 * @author wangmingxin03
 * Created on 2022-06-07
 */
public class ThreadTest {
    public static void main(String[] args) {
        AtomicLong counter = new AtomicLong();

        while (true) {
            new Thread(() -> {
                try {
                    Thread.sleep(5000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
            System.out.println("start thread ... " + counter.incrementAndGet());
        }

    }
}

 

 

创建了4000多个线程,空间撑不住了,抛异常

 

 

除了上面的问题之外,我们还可能会遇到一些:

  • OutOfMemoryError:Metaspace

元空间内存溢出

  • StackOverFlowError

栈内存溢出,线程不停的做方法调用

  • OutOfMemoryError

最常见的

一般有Java heap space、Direct buffer memory、Gc overhead limit exceeded、PermGen space

 

 

 

 

转载请注明:汪明鑫的个人博客 » Unable to create new native thread

喜欢 (0)

说点什么

您将是第一位评论人!

提醒
avatar
wpDiscuz