Why does this small Java program make MacOS restart?

问题: Code is as follows Set<Thread> threads = new HashSet<>(); Runnable r = () -> { try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedExc...

问题:

Code is as follows

Set<Thread> threads = new HashSet<>();

Runnable r = () -> {
    try {
        Thread.sleep(Long.MAX_VALUE);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
};

for (int i = 0; i < 20000; i++) {
    Thread t = new Thread(r);
    threads.add(t);
    t.start();
    if (i % 100 == 0) {
        System.out.println(i);
    }
    Thread.sleep(2);
}

When executed, I start seeing values like

0
100
200
300

as expected, and it goes until I see:

3900
4000
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:717)
    at App.main(scratch.java:24)
Java HotSpot(TM) 64-Bit Server VM warning: Exception java.lang.OutOfMemoryError occurred dispatching signal SIGINT to handler- the VM may need to be forcibly terminated

But then after a short while (10 - 20 seconds or so) MacOS decides to restart. What is the cause for the restart I am seeing here? The main thread throwing an exception, but the process having ~4000 threads sleeping causes ... what in the operating system? Is this a memory overflow or related to task scheduler of the OS?

MacOS version: 10.14.3 (18D109)
java version "1.8.0_202"
Java(TM) SE Runtime Environment (build 1.8.0_202-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.202-b08, mixed mode)

回答1:

Most likely because you either haven't given your JVM enough memory, or your computer hardware and macOS combination do not permit that many threads to be active at once. This problem is not limited to macOS but some Linux distributions, e.g. Bodhi Linux, have this limitation too. Do not be deceived by "OutOfMemoryError" - this can often mean the JVM was unable to allocate a native thread.

  • 发表于 2019-02-18 17:59
  • 阅读 ( 244 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除