Herong's Tutorial Notes on JVM
Dr. Herong Yang, Version 3.00, 2007

Stack Overflow Error

Part:   1  2 

Stack Overflow Testing Programs

The StackOverflowError is a JVM exception thrown when a stack overflow occurs because an application recurses too deeply.

I wrote the following 3 programs to try this exception:

/**
 * RecursiveCrash.java
 * Copyright (c) 2002 by Dr. Herong Yang
 */
class RecursiveCrash {
   public static void main(String[] a) {
      sub();
   }
   private static void sub() {
      sub();
   }
}
/**
 * RecursiveCrash1.java
 * Copyright (c) 2002 by Dr. Herong Yang
 */
class RecursiveCrash1 {
   static long n;
   public static void main(String[] a) {
      n = 0;
      sub();
   }
   private static void sub() {
      n++;
      try {      
         sub();
      } catch (StackOverflowError e) {
         System.out.println("Stack overflow error at: "+n);
      }
   }
}
/**
 * RecursiveCrash2.java
 * Copyright (c) 2002 by Dr. Herong Yang
 */
class RecursiveCrash2 {
   static long n;
   public static void main(String[] a) {
      n = 0;
      try {      
         sub();
      } catch (StackOverflowError e) {
         System.out.println("Stack overflow error at: "+n);
      }
   }
   private static void sub() {
      n++;
      sub();
   }
}

RecursiveCrash is simple, effective, and ready to crash any JVM.

RecursiveCrash1 is designed to catch the exception, and output the depth of the recursion.

RecursiveCrash2 is an improvement to reduce the nested try statements.

All 3 programs were compiled with J2SDK 1.4.0_02 and executed with -Xms2m and -Xmx64m options. Here is the summary of the execution results:

RecursiveCrash:

HotSpot Client:

        at RecursiveCrash.sub(RecursiveCrash.java:6)
	(repeated many times)

HotSpot Server:

        at RecursiveCrash.sub(RecursiveCrash.java:6)
	(repeated many times)

JRockit:

java.lang.StackOverflowError
        at RecursiveCrash.sub()V(Unknown Source)
	(about 35 lines of the same message)

JRockit with Management Server:

java.lang.StackOverflowError
        at RecursiveCrash.sub()V(Unknown Source)
	(about 35 lines of the same message)
java.lang.IllegalMonitorStateException
        at java.lang.Object.getMonitorIndexWithCheck(Ljava.lang.Object;
Ljava.lang.Thread;)I(Unknown Source)

(Continued on next part...)

Part:   1  2 

Dr. Herong Yang, updated in 2007
Herong's Tutorial Notes on JVM - Stack Overflow Error