Monday, March 17, 2014

Program to Crash JVM-Attempt 2- Linear Solution-Takes time

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/17/2014  
12:   */  
13:  public class CrashJVM2 implements Runnable {  
14:       static int instanceCount=0;  
15:       ArrayList<CrashJVM2> instances;  
16:       public static void main(String... args){  
17:            try{  
18:                 System.out.println("Attempting Crash JVM 2");  
19:                 ArrayList<Thread> threadInstances=new ArrayList<Thread>();  
20:                 Thread t;  
21:                 //linear solution-takes more time to crash  
22:                 while(true){  
23:                      ++instanceCount;  
24:                      t=new Thread(new CrashJVM2());  
25:                      t.start();  
26:                      threadInstances.add(t);  
27:                 }  
28:            }catch(Throwable t){  
29:                 if(t instanceof OutOfMemoryError){  
30:                      System.out.println("JVM Crashed due to OutOfMemoryError!");  
31:                 }  
32:                 t.printStackTrace();  
33:            }  
34:       }  
35:       @Override  
36:       public void run() {  
37:            // TODO Auto-generated method stub  
38:            System.out.println("Created Instance : "+instanceCount);  
39:            int count=0;  
40:            System.out.println("Starting Infinite Loop!");  
41:            while(true){  
42:                 System.out.println("Inside run() for run : "+count);  
43:                 ++count;  
44:            }  
45:       }  
46:  //End of CrashJVM2  
47:  }  

No comments:

Post a Comment