<p>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.</p>

<p>Anybody has any idea?</p>

[{'answer_id': 65237, 'author': 'Dan Dyer', 'author_id': 5171, 'author_profile': 'https://Stackoverflow.com/users/5171', 'pm_score': 7, 'selected': False, 'text': '<p><a href="http://en.wikipedia.org/wiki/Java_Native_Interface" rel="noreferrer">JNI</a>.  In fact, with JNI, crashing is the default mode of operation.  You have to work extra hard to get it not to crash.</p>\n'}, {'answer_id': 65289, 'author': 'Herms', 'author_id': 1409, 'author_profile': 'https://Stackoverflow.com/users/1409', 'pm_score': 3, 'selected': False, 'text': '<p>Depends on what you mean by crash.</p>\n\n<p>You can do an infinite recursion to make it run out of stack space, but that\'ll crash "gracefully".  You\'ll get an exception, but the JVM itself will be handling everything.</p>\n\n<p>You can also use JNI to call native code.  If you don\'t do it just right then you can make it crash hard.  Debugging those crashes is "fun" (trust me, I had to write a big C++ DLL that we call from a signed java applet). :)</p>\n'}, {'answer_id': 65290, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 0, 'selected': False, 'text': '<p>If you change that infinite for loop to a recursive call to the same function, then you would get a stack overflow exception:</p>\n\n<pre><code>public static void main(String[] args) {\n    causeStackOverflow();\n}\n\npublic void causeStackOverflow() {\n    causeStackOverflow();\n}\n</code></pre>\n'}, {'answer_id': 65291, 'author': 'Leigh Caldwell', 'author_id': 3267, 'author_profile': 'https://Stackoverflow.com/users/3267', 'pm_score': 4, 'selected': True, 'text': '<p>The closest thing to a single "answer" is <code>System.exit()</code> which terminates the JVM immediately without proper cleanup. But apart from that, native code and resource exhaustion are the most likely answers. Alternatively you can go looking on Sun\'s bug tracker for bugs in your version of the JVM, some of which allow for repeatable crash scenarios. We used to get semi-regular crashes when approaching the 4 Gb memory limit under the 32-bit versions (we generally use 64-bit now).</p>\n'}, {'answer_id': 65332, 'author': 'Dave L.', 'author_id': 3093, 'author_profile': 'https://Stackoverflow.com/users/3093', 'pm_score': 4, 'selected': False, 'text': "<p>A perfect JVM implementation will never crash.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n"}, {'answer_id': 65610, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>The book <a href="http://www.amazon.co.uk/Java-Virtual-Machine-Series/dp/1565921941" rel="nofollow noreferrer">Java Virtual Machine</a> by Jon Meyer has an example of a series of bytecode instructions that caused the JVM to core dump. I can\'t find my copy of this book. If anyone out there has one please look it up and post the answer.</p>\n'}, {'answer_id': 74780, 'author': 'ralfs', 'author_id': 13107, 'author_profile': 'https://Stackoverflow.com/users/13107', 'pm_score': 7, 'selected': False, 'text': "<p>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:</p>\n\n<ol>\n<li>Use JNI and crash in the native code.</li>\n<li>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 <strong>java.lang.Thread</strong>). Just change them via reflection and the VM will crash sooner or later.</li>\n<li>All VMs have bugs, so you just have to trigger one.</li>\n</ol>\n\n<p>For the last method I have a short example, which will crash a Sun Hotspot VM quiet nicely:</p>\n\n<pre><code>public class Crash {\n    public static void main(String[] args) {\n        Object[] o = null;\n\n        while (true) {\n            o = new Object[] {o};\n        }\n    }\n}\n</code></pre>\n\n<p>This leads to a stack overflow in the GC so you will get no StackOverflowError but a real crash including a hs_err* file.</p>\n"}, {'answer_id': 74867, 'author': 'eckes', 'author_id': 13189, 'author_profile': 'https://Stackoverflow.com/users/13189', 'pm_score': 2, 'selected': False, 'text': '<p>If you define a crash as an process abort because of a unhandled situation (i.e. no Java Exception or Error), then this can not be done from within Java (unless you have permission to use the sun.misc.Unsafe class). This the whole point of managed code.</p>\n\n<p>Typical crashes in native code happen by de-referencing pointers to wrong memory areas (null address or missaligned). Another source could be illegal machine instructions (opcodes) or unhandled signals from library or kernel calls. Both can be triggered if the JVM or the system libraries have bugs.</p>\n\n<p>For example JITed (generated) code, native methods or system calls (graphics driver) can have problems leading to real crashes (it was quite common to get a crash when you used ZIP functions and they ran out of memory). In those cases the crash handler of the JVM kicks in and dumps the state. It could also generate a OS core file (Dr. Watson on Windows and core dump on *nix).</p>\n\n<p>On Linux/Unix you can easyly make a JVM crash by sending it a Signal to the running process. Note: you should not use <code>SIGSEGV</code> for this, since Hotspot catches this signal and re-throws it as a NullPointerException in most places. So it is better to send a <code>SIGBUS</code> for example.</p>\n'}, {'answer_id': 107442, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>on winxpsp2 w/wmp10 jre6.0_7</p>\n\n<p>Desktop.open(uriToAviOrMpgFile)</p>\n\n<p>This causes a spawned thread to throw an uncaught Throwable and crashes hotspot</p>\n\n<p>YMMV</p>\n'}, {'answer_id': 152298, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>here is a detailed explanation on what causes JVM to core dump (i.e. crash): \n<a href="http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_17534" rel="nofollow noreferrer">http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_17534</a></p>\n'}, {'answer_id': 798997, 'author': 'Brian Knoblauch', 'author_id': 15689, 'author_profile': 'https://Stackoverflow.com/users/15689', 'pm_score': 0, 'selected': False, 'text': "<p>I'm doing it now, but not entirely sure how...  :-)  JVM (and my app) sometimes just completely disappear.  No errors thrown, nothing logged.  Goes from working to not running at all instantly with no warning.</p>\n"}, {'answer_id': 799757, 'author': 'Peter Lawrey', 'author_id': 57695, 'author_profile': 'https://Stackoverflow.com/users/57695', 'pm_score': 2, 'selected': False, 'text': '<p>If you want to pretend you have run out of memory you can do</p>\n\n<pre><code>public static void main(String[] args) {\n    throw new OutOfmemoryError();\n}\n</code></pre>\n\n<p>I know a couple of way to cause the JVM dump an error file by calling native methods (ones which are built in), but its probably best you not know how to do this. ;)</p>\n'}, {'answer_id': 799781, 'author': 'Jared', 'author_id': 14744, 'author_profile': 'https://Stackoverflow.com/users/14744', 'pm_score': 2, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 820021, 'author': 'Michael Borgwardt', 'author_id': 16883, 'author_profile': 'https://Stackoverflow.com/users/16883', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 1378388, 'author': 'Dave Griffiths', 'author_id': 15379, 'author_profile': 'https://Stackoverflow.com/users/15379', 'pm_score': 6, 'selected': False, 'text': "<p>Use this:</p>\n<pre><code>import sun.misc.Unsafe;\n\npublic class Crash {\n    private static final Unsafe unsafe = Unsafe.getUnsafe();\n    public static void crash() {\n        unsafe.putAddress(0, 0);\n    }\n    public static void main(String[] args) {\n        crash();\n    }\n}\n</code></pre>\n<p>This class must be on the boot classpath because it is using trusted code,so run like this:</p>\n<blockquote>\n<p>java -Xbootclasspath/p:. Crash</p>\n</blockquote>\n<p><strong>EDIT</strong>: Simplified version with pushy's suggestion:</p>\n<pre><code>Field f = Unsafe.class.getDeclaredField(&quot;theUnsafe&quot;);\nf.setAccessible(true);\nUnsafe unsafe = (Unsafe) f.get(null);\nunsafe.putAddress(0, 0);\n</code></pre>\n"}, {'answer_id': 2849632, 'author': 'Rob Mayhew', 'author_id': 49393, 'author_profile': 'https://Stackoverflow.com/users/49393', 'pm_score': 4, 'selected': False, 'text': '<p>This code will crash the JVM in nasty ways</p>\n\n<pre><code>import sun.dc.pr.PathDasher; \n\npublic class Crash\n{\n     public static void main(String[] args)\n     {    \n        PathDasher dasher = new PathDasher(null) ;\n     }\n}\n</code></pre>\n'}, {'answer_id': 7291092, 'author': 'Prabath Siriwardena', 'author_id': 804637, 'author_profile': 'https://Stackoverflow.com/users/804637', 'pm_score': 4, 'selected': False, 'text': '<p>If you want to crash JVM - use the following in Sun JDK 1.6_23 or below:</p>\n\n<pre><code>Double.parseDouble("2.2250738585072012e-308");\n</code></pre>\n\n<p>This is due to a <a href="http://www.theregister.co.uk/2011/02/07/java_denial_of_service_bug/" rel="noreferrer">bug</a> in Sun JDK - also found in OpenJDK.\nThis is fixed from Oracle JDK 1.6_24 onwards.</p>\n'}, {'answer_id': 11636338, 'author': 'George Armhold', 'author_id': 93995, 'author_profile': 'https://Stackoverflow.com/users/93995', 'pm_score': 5, 'selected': False, 'text': '<p>I came here because I also ran into this question in <a href="https://rads.stackoverflow.com/amzn/click/com/1934356344" rel="noreferrer" rel="nofollow noreferrer">The Passionate Programmer</a>, by Chad Fowler. For those who don\'t have access to a copy, the question is framed as a kind of filter/test for candidates interviewing for a position requiring "really good Java programmers."</p>\n\n<p>Specifically, he asks:</p>\n\n<blockquote>\n  <p>How would you write a program, in pure Java, that would cause the Java Virtual Machine to crash?</p>\n</blockquote>\n\n<p>I\'ve programmed in Java for over 15 years, and I found this question to be both puzzling and unfair. As others have pointed out, Java, as a managed language, is specifically designed <em>not to crash</em>. Of course there are always JVM bugs, but:</p>\n\n<ol>\n<li>After 15+ years of production-level JREs, it\'s rare.</li>\n<li>Any such bugs are likely to be patched in the next release, so how likely are you as a programmer to run into and recall the details of the current set of JRE show-stoppers?</li>\n</ol>\n\n<p>As others have mentioned, some native code via JNI is a sure way to crash a JRE. But the author specifically mentioned <em>in pure Java</em>, so that\'s out.</p>\n\n<p>Another option would be to feed the JRE bogus byte codes; it\'s easy enough to dump some garbage binary data to a .class file, and ask the JRE to run it:</p>\n\n<pre><code>$ echo \'crap crap crap\' &gt; crap.class\n$ java crap\nException in thread "main" java.lang.ClassFormatError: Incompatible magic value 1668440432 in class file crap\n</code></pre>\n\n<p>Does that count? I mean the JRE itself hasn\'t crashed; it properly detected the bogus code, reported it, and exited. </p>\n\n<p>This leaves us with the most obvious kinds of solutions such as blowing the stack via recursion, running out of heap memory via object allocations, or simply throwing <code>RuntimeException</code>. But this just causes the JRE to exit with a <code>StackOverflowError</code> or similar exception, which, again <em>is not really a crash</em>.</p>\n\n<p>So what\'s left? I\'d really love to hear what the author really had in mind as a proper solution.</p>\n\n<p><strong>Update</strong>: Chad Fowler <a href="https://twitter.com/chadfowler/status/227845163031072768" rel="noreferrer">responded here</a>.</p>\n\n<p>PS: it\'s an otherwise great book. I picked it up for moral support while learning Ruby.</p>\n'}, {'answer_id': 22905184, 'author': 'RRM', 'author_id': 1439122, 'author_profile': 'https://Stackoverflow.com/users/1439122', 'pm_score': 3, 'selected': False, 'text': '<p>shortest possible way :)</p>\n\n<pre><code>public class Crash\n{\n    public static void main(String[] args)\n    {\n        main(args);\n    }\n}\n</code></pre>\n'}, {'answer_id': 28650035, 'author': 'Hot Licks', 'author_id': 581994, 'author_profile': 'https://Stackoverflow.com/users/581994', 'pm_score': 5, 'selected': False, 'text': '<p>Last time I tried this would do it:</p>\n\n<pre><code>public class Recur {\n    public static void main(String[] argv) {\n        try {\n            recur();\n        }\n        catch (Error e) {\n            System.out.println(e.toString());\n        }\n        System.out.println("Ended normally");\n    }\n    static void recur() {\n        Object[] o = null;\n        try {\n            while(true) {\n                Object[] newO = new Object[1];\n                newO[0] = o;\n                o = newO;\n            }\n        }\n        finally {\n            recur();\n        }\n    }\n}\n</code></pre>\n\n<p>First part of generated log file:</p>\n\n<pre><code>#\n# An unexpected error has been detected by Java Runtime Environment:\n#\n#  EXCEPTION_STACK_OVERFLOW (0xc00000fd) at pc=0x000000006dad5c3d, pid=6752, tid=1996\n#\n# Java VM: Java HotSpot(TM) 64-Bit Server VM (11.2-b01 mixed mode windows-amd64)\n# Problematic frame:\n# V  [jvm.dll+0x2e5c3d]\n#\n# If you would like to submit a bug report, please visit:\n#   http://java.sun.com/webapps/bugreport/crash.jsp\n#\n\n---------------  T H R E A D  ---------------\n\nCurrent thread (0x00000000014c6000):  VMThread [stack: 0x0000000049810000,0x0000000049910000] [id=1996]\n\nsiginfo: ExceptionCode=0xc00000fd, ExceptionInformation=0x0000000000000001 0x0000000049813fe8 \n\nRegisters:\nEAX=0x000000006dc83090, EBX=0x000000003680f400, ECX=0x0000000005d40ce8, EDX=0x000000003680f400\nESP=0x0000000049813ff0, EBP=0x00000000013f2df0, ESI=0x00000000013f0e40, EDI=0x000000003680f400\nEIP=0x000000006dad5c3d, EFLAGS=0x0000000000010206\n</code></pre>\n'}, {'answer_id': 35111507, 'author': 'Sankarganesh Eswaran', 'author_id': 2629588, 'author_profile': 'https://Stackoverflow.com/users/2629588', 'pm_score': -1, 'selected': False, 'text': "<p>If a 'Crash' is anything that interrupts the jvm/program from normal termination, then an Un-handled exception could do this.</p>\n\n<pre><code>public static void main(String args[]){\n   int i = 1/0;\n   System.out.print(i); // This part will not be executed due to above  unhandled exception\n  }\n</code></pre>\n\n<p>So, it depends on what type of CRASH ?!</p>\n"}, {'answer_id': 37839185, 'author': 'henry', 'author_id': 640224, 'author_profile': 'https://Stackoverflow.com/users/640224', 'pm_score': 3, 'selected': False, 'text': '<p>Not a crash, but closer to a crash than the accepted answer of using <code>System.exit</code></p>\n\n<p>You can halt the JVM by calling</p>\n\n<p><code>Runtime.getRuntime().halt( status )</code></p>\n\n<p>According to the docs :-</p>\n\n<blockquote>\n  <p>"this method does not cause shutdown hooks to be started and does not run uninvoked finalizers if finalization-on-exit has been enabled". </p>\n</blockquote>\n'}, {'answer_id': 38031059, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>Shortest? Use Robot class to trigger CTRL+BREAK. I spotted this when I was trying to close my program without closing console (It had no 'exit' functionality).</p>\n"}, {'answer_id': 46211034, 'author': 'Lightfire228', 'author_id': 2716305, 'author_profile': 'https://Stackoverflow.com/users/2716305', 'pm_score': 2, 'selected': False, 'text': "<p>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.</p>\n\n<pre><code>public class Crash {\n    public static void main(String[] args) {\n\n        Runnable[] arr = new Runnable[1];\n        arr[0] = () -&gt; {\n\n            while (true) {\n                new Thread(arr[0]).start();\n            }\n        };\n\n        arr[0].run();\n    }\n}\n</code></pre>\n\n<p>This gave me the output (after 5 minutes, watch your ram) </p>\n\n<pre><code>An unrecoverable stack overflow has occurred.\n#\n# A fatal error has been detected by the Java Runtime Environment:\n#\n#  EXCEPTION_STACK_OVERFLOW (0xc00000fd) at pc=0x0000000070e53ed7, pid=12840, tid=0x0000000000101078\n#\n# JRE version: Java(TM) SE Runtime Environment (8.0_144-b01) (build 1.8.0_144-b01)\n# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.144-b01 mixed mode windows-amd64 compressed oops)\n# Problematic frame:\n# \n</code></pre>\n"}, {'answer_id': 55381501, 'author': 'mszmurlo', 'author_id': 1483318, 'author_profile': 'https://Stackoverflow.com/users/1483318', 'pm_score': 1, 'selected': False, 'text': '<p>Does this count ?</p>\n\n<pre><code>long pid = ProcessHandle.current().pid();\ntry { Runtime.getRuntime().exec("kill -9 "+pid); } catch (Exception e) {}\n</code></pre>\n\n<p>It only works for Linux and from Java 9.</p>\n\n<p>For some reason I don\'t get, <code>ProcessHandle.current().destroyForcibly();</code> doesn\'t kill the JVM and throws <code>java.lang.IllegalStateException</code> with the message <em>destroy of current process not allowed</em>.</p>\n'}, {'answer_id': 57697108, 'author': 'charlie arehart', 'author_id': 90802, 'author_profile': 'https://Stackoverflow.com/users/90802', 'pm_score': 2, 'selected': False, 'text': '<p>If by "crash" you mean an abrupt abort of the JVM, <strong>such as would cause the JVM to write out to its hs_err_pid%p.log</strong>, you can do it this way.</p>\n\n<p>Set the-Xmx arg to a tiny value and tell the JVM to force a crash on outofmemory:</p>\n\n<pre><code> -Xmx10m -XX:+CrashOnOutOfMemoryError\n</code></pre>\n\n<p>To be clear, without the second arg above, it would just result in the jvm <strong>terminating</strong> with an OutOfMemoryError, but it would not "crash" or abruptly abort the jvm. </p>\n\n<p>This technique proved helpful when I was trying to test the JVM -XX:ErrorFile arg, which controls where such an hs_err_pid log should be written. I had found this post here, while trying to find ways to force such a crash. When I later found the above worked as the easiest for my need, I wanted to add it to the list here.</p>\n\n<p>Finally, FWIW, if anyone may test this when they already have an -Xms value set in your args (to some larger value than above), you\'ll want to remove or change that also, or you will get not a crash but simply a failure of the jvm to start, reporting "Initial heap size set to a larger value than the maximum heap size". (That wouldn\'t be obvious if running the JVM as service, such as with some app servers. Again, it bit me, so I wanted to share it.)</p>\n'}, {'answer_id': 60860170, 'author': 'Frank Teng', 'author_id': 10787741, 'author_profile': 'https://Stackoverflow.com/users/10787741', 'pm_score': 1, 'selected': False, 'text': '<p>Running into this issue when trying to replicate the JVM crash.</p>\n\n<p>Jni works, but it needs to be tweaked for different platforms.\nEventually, I use this combination to make JVM crash</p>\n\n<ol>\n<li>Start the application with this JVM options <code>-XX:+CrashOnOutOfMemoryError</code></li>\n<li>Use a <code>long[] l = new long[Integer.MAX_VALUE];</code> to trigger the OOM</li>\n</ol>\n\n<p>Then JVM will crash and generate the crash log. </p>\n'}]
['https://Stackoverflow.com/questions/65200', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9195/']