Monday, March 17, 2014

Program to Crash JVM-Attempt 1- Exponential infinite loop

1:  package com.mridul.java.dump;  
2:  import java.util.ArrayList;  
3:  /**Program to crash the JVM  
4:   * as per a problem on the Passionate  
5:   * Programmer book. This solution results  
6:   * in an OutOfMemory Error. The actual  
7:   * solution might require JNI as per  
8:   * discussion on forums   
9:   * WARNING: WILL CRASH YOUR MACHINE REQUIRING REBOOT  
10:   * @author Mridul Jayan  
11:   * @date 03/09/2014  
12:   */  
13:  public class CrashJVM implements Runnable {  
14:       @Override  
15:       public void run() {  
16:            System.out.println("Attempting to Crash JVM!");  
17:            ArrayList<CrashJVM> crashJVM=new ArrayList<CrashJVM>();  
18:            int ctr=0;  
19:            double expctr=0.0;  
20:            //exponentials tend to scale faster  
21:            while(true){  
22:                 expctr=Math.exp((double)ctr);  
23:                 for(double ictr=0.0;ictr<expctr;ictr++){  
24:                      crashJVM.add(new CrashJVM());  
25:                      System.out.println("Created Instance "+(++ctr));  
26:                 }  
27:            }  
28:       }  
29:       public static void main(String[] args) {  
30:            try {  
31:                 ArrayList<Thread> childThread=new ArrayList<Thread>();  
32:                 while(true){  
33:                      Thread t=new Thread(new CrashJVM());  
34:                      childThread.add(t);  
35:                      t.start();  
36:                 }  
37:            }catch(Throwable t){  
38:                 if(t instanceof OutOfMemoryError){  
39:                      System.out.println("The JVM has crashed!");  
40:                 }  
41:                 t.printStackTrace();  
42:            }  
43:       }  
44:  //End of CrashJVM  
45:  }  

No comments:

Post a Comment