By writing Java code to make Jvm collapse

In the book the authors propose a question to see a "how to make Jvm by writing Java code collapse", after I saw do not know. With questions about the investigation, Baidu know there are such an answer:

  1 package jvm;

  2

  3 public class Crash {

  4     public static void main(String[] args) {

  5

  6 // Object [] o = { "abc"}; assign an initial value, will not be affected.

  7         Object[] o = null;

  8

  9         while (true) {

  10             o = new Object[] { o };

  11 // output, then, jvm will not collapse.

  12             //System.out.println(o);

  13         }

  14     }

  15 }

  After running ten seconds, the console this error:

  Exception in thread "main" java.lang.OutOfMemoryError: Java 
heap space

  at jvm.Crash.main(Crash.java:10)

  Obviously, beyond the memory error.

  I have the original program arbitrarily changed a bit, as assigned initial value, had no effect on the program.

  But I will die cycle o When the output console, jvm has not been actually collapse, why the output, then it will not be out of memory space?

  My opinion, the original program can make Jvm collapse, because the cycle of death by old object, and constantly create a new object, the object that is created is a reference to each other, so the GC will not recover them, resulting in a stack overflow.

  Follow this example, I wrote a simple class imitate the example array of programs, as follows:

  1 package jvm;

  2

  3 public class JvmBean {

  4

  5     JvmBean bean = new JvmBean(this);

  6

  7     public JvmBean(JvmBean bean){

  8         this.bean = bean;

  9     }

  10 }

  Then simple test, as follows:

  1 package jvm;

  2

  3 public class MyCrash {

  4

  5     public static void main(String[] args) {

  6         JvmBean j = null;

  7         while(true){

  8             j = new JvmBean(j);

  9 // regardless of the output is not output, jvm will collapse

  10             //System.out.println(j);

  11         }

  12     }

  13 }

Guess you like

Origin www.cnblogs.com/dingzhenor/p/12161498.html