6

In one of my past interviews , someone asked me to write a code to crash the JVM. I said System.exit(). Is this correct? Are there any better answers?

clarification: I can include my piece of code during development and deploy. It is not that JVM is already running and I have to write a hacking code to crash the other JVM.

java_mouse
  • 2,069
  • 4
  • 21
  • 30
  • 2
    No, that doesn't **crash** the VM. You can easily trigger memory overflow though with a infinite loop. – Johan Sjöberg Oct 14 '11 at 17:06
  • 1
    `System.exit()` just terminates VM - This is a duplicate question - look here [How do you crash a JVM?](http://stackoverflow.com/questions/65200/how-do-you-crash-a-jvm) – ring bearer Oct 14 '11 at 17:08
  • I can include the code during my development. – java_mouse Oct 14 '11 at 17:08
  • 4
    This interview question _does not make sense_ on the first place! – CoolBeans Oct 14 '11 at 17:09
  • 2
    Yeah but memory overflow is a program crash, not a VM crash. To have a genuine JVM crash you'd have to find and use an actual JVM bug - obviously the JVM crashing isn't part of normal expected runtime. – Vala Oct 14 '11 at 17:10
  • @Thor84no, couldn't agree with you more. – aioobe Oct 14 '11 at 18:01

5 Answers5

19

You can use the Unsafe class which is unsafe to use as you might guess.

public static void main(String... args) throws Exception {
    getUnsafe().getByte(0);
}

private static Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException {
    Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
    theUnsafe.setAccessible(true);
    return (Unsafe) theUnsafe.get(null);
}

prints

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007ff1c2f23368, pid=2630, tid=140676351506176
#
# JRE version: 7.0-b147
# Java VM: Java HotSpot(TM) 64-Bit Server VM (21.0-b17 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# V  [libjvm.so+0x82c368]  Unsafe_GetNativeByte+0xa8
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /nfs/peter/IdeaProjects/scratch/hs_err_pid2630.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.sun.com/bugreport/crash.jsp
#

I have used this to test when a change has been made to a file. I made the change and crashed the JVM to ensure something else wasn't flushing or something later. Then I check I saw the update I expected.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
16

I don't think politely requesting that the JVM terminates really counts as "crashing" it. You'd have to ask the interviewew exactly what they meant by "crash". For example:

  • Would forcing a stack overflow or an out-of-memory condition count?
  • Can you use JNI or any other sort of native code?
  • Tell me what exact VM version you're running, and I'll try to find a JIT compiler bug...

(There have certainly been JIT compiler problems in the past - ages ago I had a pure Java program which would consistently segfault, but could be "fixed" by making what looked like a no-op change.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
5

Simple: Either blow the stack with infinite recursion or run the JVM out of object heap.

More complicated would be to run the JVM out of internal heap -- you could probably do this with some sort of class loading loop, but it would take work.

Otherwise you'd have to exploit some sort of bug, or at least drop into JNI.

public class Recur {
public static void main(String[] argv) {
    recur();
}
static void recur() {
    Object[] o = null;
    try {
        while(true) {
            Object[] newO = new Object[1];
            newO[0] = o;
            o = newO;
        }
    }
    finally {
        recur();
    }
}
}

C:\JavaTools>java Recur
#
# An unexpected error has been detected by Java Runtime Environment:
#
#  EXCEPTION_STACK_OVERFLOW (0xc00000fd) at pc=0x000000006dad5c3d, pid=6816, tid
=5432
#
# Java VM: Java HotSpot(TM) 64-Bit Server VM (11.2-b01 mixed mode windows-amd64)

# Problematic frame:
# V  [jvm.dll+0x2e5c3d]
#
# An error report file with more information is saved as:
# C:\JavaTools\hs_err_pid6816.log
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
#

Ta da!!

(And you can restrict access to Unsafe, but not any of the above.)

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
  • This is just running out of Java stack or heap memory, it's not the same as crashing the JVM. See Peter Lawrey's answer to what a JVM crash looks like. – Steve Kuo Oct 14 '11 at 17:50
  • The definition of "crash" is somewhat subjective. The Unsafe scheme is something I hadn't thought of. But running the JVM out of internal heap would likely result in a "true" crash. – Hot Licks Oct 14 '11 at 19:38
  • (Note that the JVM "usually" handles infinite recursion with an only an unhandled exception shutdown, but it's highly context dependent.) – Hot Licks Oct 14 '11 at 19:48
0

To crash the entire computer, I would do:

public static void crashComputer() {
    while(true) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    crashComputer();
                }
            }
        });
        thread.start();
    }
}

public static void crashJVM() {
    while(true)
        crashJVM();
}

The crashComputer function takes about 2 seconds to crash the entire computer. You can stop it from crashing by holding power button.

The crashJVM function crashed only the JVM by overloading the stack, causing a stack overflow (That's where the name of this website comes from).

WARNING: Use at your own risk. This will not damage your computer, but I'm not taking the blame if you forget to click save on a document or something.

Aaron Esau
  • 1,083
  • 3
  • 15
  • 31
-1

Crashing the application can be done using the OutOfMemoryError also.

public class StringOutOfMemory {
    public static void main(String[] args) {
        int i = 0;
        StringBuilder s = new StringBuilder("a");
        while (true) {
            s.append("ahgsdgjsdffsdfhsdgfsdfsdsfhdsgksdgkfgsdkfkdghfksdkfsdkfdkjfskdfkjsdfkdksdkdfjksjkhsdfjkfsdkjfsdhjkfsdjkfhdjkfkjsdfkjdsjkfd");
            System.out.println(i++); 
        }
    }
}

Output:

java.lang.OutOfMemoryError}}}
Dennis Meng
  • 5,109
  • 14
  • 33
  • 36