How do you crash a JVM?

I was reading a book on programming skills wherein the author asks the interviewee, "How do you crash a JVM?" I thought that you could do so by writing an infinite for-loop that would eventually use up all the memory.

Anybody has any idea?


I wouldn't call throwing an OutOfMemoryError or StackOverflowError a crash. These are just normal exceptions. To really crash a VM there are 3 ways:

  1. Use JNI and crash in the native code.
  2. If no security manager is installed you can use reflection to crash the VM. This is VM specific, but normally a VM stores a bunch of pointers to native resources in private fields (e.g. a pointer to the native thread object is stored in a long field in java.lang.Thread). Just change them via reflection and the VM will crash sooner or later.
  3. All VMs have bugs, so you just have to trigger one.

For the last method I have a short example, which will crash a Sun Hotspot VM quiet nicely:

public class Crash {
    public static void main(String[] args) {
        Object[] o = null;

        while (true) {
            o = new Object[] {o};
        }
    }
}

This leads to a stack overflow in the GC so you will get no StackOverflowError but a real crash including a hs_err* file.


JNI. In fact, with JNI, crashing is the default mode of operation. You have to work extra hard to get it not to crash.