Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scenarios under which JVM gets killed?

Tags:

java

jvm

scala

I am thinking of all the scenarios where JVM could get killed because of Programming Errors?

SomeOne claimed that java.lang.OutOfMemoryError: Java heap space will not cause JVM to get killed, but when I run my program to assert, this was not found to be true. I tried this program

Where can I find list of recoverable and un-receoverable errors?

Thanks

like image 995
daydreamer Avatar asked Jan 27 '26 12:01

daydreamer


1 Answers

The JVM will stop

  • when it crashes due to a bug in the JVM
  • when all the non-daemon threads stop running
  • when invoking System.exit()

An Exception or an Error being thrown never stops the JVM. What it can do, though, if it's not caught, if to cause the thread from which it's called to terminate its execution. And if it's the last non-daemon thread to run, then the JVM will stop.

Example:

public static void main(String[] args) {
    Runnable r = new Runnable() {
        public void run() {
            while (true) {
                System.out.println("still running...");
                try {
                    Thread.sleep(1000L);
                }
                catch (InterruptedException e) {
                    // ignore: I don't want to die
                }
            }
        }
    };

    Thread neverEndingThread = new Thread(r);
    neverEndingThread.start();

    List<byte[]> arrays = new ArrayList<>();
    for (int i = 0; i < 1000; i++) {
        byte[] hugeArray = new byte[2_000_000_000];
        arrays.add(hugeArray);
    }
    System.out.println(arrays);
}

Executing this code will start a new thread, and then will cause an OutOfMemoryError to be thrown from the main thread. Since this error is not caught by the main thread, the main thread stops executing. But the JVM doesn't stop, because the never ending thread continues to run.

like image 53
JB Nizet Avatar answered Jan 30 '26 04:01

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!