Why does this small Java program make MacOS restart?

  • A+

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) 


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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: