java 栈溢出问题排查

2023-03-31
1 min read

如何排查:java.lang.OutOfMemoryError: unable to create native thread

java.lang.OutOfMemoryError: unable to create native thread

测试代码

for (int i = 0; i < 3500; i++) {
    new Thread(() -> {
        try {
            try {Thread.sleep(5000L);}
            catch (InterruptedException e) {e.printStackTrace();}
            TimeUnit.HOURS.sleep(1);
            log.info("\n==== [log]: {} {}", "sleep over",Thread.currentThread().getName());
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }).start();
}

相关指令

  • 查看进程的线程数量

    jstack -l PID | grep 'java.lang.Thread.State' | wc -l
    jstack -l PID | grep 'java.lang.Thread.State: RUNNABLE' | wc -l
    jstack -l PID | grep 'java.lang.Thread.State: TIMED_WAITING'  | wc -l
    jstack -l PID | grep 'java.lang.Thread.State: WAITING' | wc -l
    jstack -l PID | grep 'java.lang.Thread.State:BLOCKED'  | wc -l
    jstack -l PID | grep 'Java-level deadlock'  | wc -l
    
  • 查看进程的线程状态

    jstack -l PID | grep 'java.lang.Thread.State'
    
  • 查看进程的线程信息

    jstack -l PID
    

    返回信息,可以看到阻塞的代码信息

    "Thread-4050" #4136 prio=5 os_prio=31 cpu=1.00ms elapsed=546.19s tid=0x0000000130247000
           nid=0x354103 waiting on condition  [0x00000004b9a2e000]
      java.lang.Thread.State: TIMED_WAITING (sleeping)
      at java.lang.Thread.sleep(java.base@11.0.13/Native Method)
      at java.lang.Thread.sleep(java.base@11.0.13/Thread.java:334)
      at java.util.concurrent.TimeUnit.sleep(java.base@11.0.13/TimeUnit.java:446)
      at com....controller.CommentsController$$M$_jr_0E50A6F6C7FE22B0_1
           .lambda$0(CommentsController.java:129)
      at com....controller.CommentsController$$Lambda$964$$M$_jr_0E50A6F6C7FE22B0_1
           /0x0000000800e11c40.run(Unknown Source)
      at java.lang.Thread.run(java.base@11.0.13/Thread.java:829)