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-loo
Broken hardware can crash any program. I once had an app crash reproducably on a specific machine while running fine on other machines with the exact same setup. Turns out that machine had faulty RAM.
JNI is a large source of crashes. You can also crash using the JVMTI interface since that needs to be written in C/C++ as well.
If you create a thread process that infinitely spawns more threads (which spawn more threads, which...) you'll eventually cause a stack overflow error in the JVM itself.
public class Crash {
public static void main(String[] args) {
Runnable[] arr = new Runnable[1];
arr[0] = () -> {
while (true) {
new Thread(arr[0]).start();
}
};
arr[0].run();
}
}
This gave me the output (after 5 minutes, watch your ram)
An unrecoverable stack overflow has occurred.
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_STACK_OVERFLOW (0xc00000fd) at pc=0x0000000070e53ed7, pid=12840, tid=0x0000000000101078
#
# JRE version: Java(TM) SE Runtime Environment (8.0_144-b01) (build 1.8.0_144-b01)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.144-b01 mixed mode windows-amd64 compressed oops)
# Problematic frame:
#
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:
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.
Running into this issue when trying to replicate the JVM crash.
Jni works, but it needs to be tweaked for different platforms. Eventually, I use this combination to make JVM crash
-XX:+CrashOnOutOfMemoryError
long[] l = new long[Integer.MAX_VALUE];
to trigger the OOMThen JVM will crash and generate the crash log.
A perfect JVM implementation will never crash.
To crash a JVM, aside from JNI, you need to find a bug in the VM itself. An infinite loop just consumes CPU. Infinitely allocating memory should just cause OutOfMemoryError's in a well built JVM. This would probably cause problems for other threads, but a good JVM still should not crash.
If you can find a bug in the source code of the VM, and for example cause a segmentation fault in the memory usage of the implementation of the VM, then you can actually crash it.