Why does this small Java program make MacOS restart? Why does this small Java program make MacOS restart? multithreading multithreading

Why does this small Java program make MacOS restart?


Despite the fact that the console shows the program has finished, the JVM process still runs until all resources are released. Meanwhile, your OS is out of threads, slow and unstable, which cause lagging in all processes, including the JVM finalization. As a self defense, the OS triggers a kernel panic. And that is why your MacOS restarts.

*OS - Operating System


Java was built in the 90's, when there were only multi-core processors.

Surely Java has evolved, as have modern-day processors. Nowadays we have 8-core processors, with large caches (e.g: 12MB).

Even though concurrent processing has evolved much, Java is still designed around the 1-core processor model. But, enough with history, let me explain very very simply what happens.

Just by simply creating a new thread in Java, we waste a lot of memory.

Every thread consumes around ~ 512KB - 1MB, depending on your JVM version (see how much memory a thread takes in java and Java Thread: Retained Memory). Bearing this in mind, when continuously creating new Threads, at some point they will consume all of the heap's memory.

Now, I have never tried this on my own, but I assume that your computer's operating system shuts down/restarts due to the "out of memory" error, as a countermeasure. (This is much like the triple fault, that caused the infamous "Blue Screen of Death" on Windows, where the machine needed to restart to reset the CPU's state)

One possible solution for this, is to manually set the maximum heap size to be used by the JVM. Thus, when your program completely utilises the pre-allocated heap, it will not cause a shutdown. Please refer to this SO question on how to do this.


I just stumbled on the same problem today. Here's some python code triggering the same kernel panic on 10.15.5 (Catalina). Tested it on two macs to make sure this is not a hardware problem:

https://github.com/ephes/django_async/blob/master/measure_threads_memory.py

Maybe I go and write a bug report.