Let’s make the stack explode in Java!

In one of my lectures about memory management in Java, I was looking for a quick and simple way to demonstrate the influence of local variables on the stack memory usage. So what came to my mind was this:

Local variables, including method parameters, are stored within a stack frame. As the stack size is limited, the maximum number of stack frames allowed on the stack depends on the size of each frame. Thus, when you declare some local variables within a method that recursively calls itself, the number of recursive calls until a stack overflow occurs should be lower than without the local variables.

Here is a program that allows you to demonstrate the expected behavior.

/**
 * This program will intentionally cause a stack overflow.
 *
 * CC BY-NC
 * This work is licensed under a Creative Commons
 * Attribution-NonCommercial 4.0 International License.
 *
 * @author Andre M. Maier
 * @version 1.0
 */
public class Demo {

   public static void main( String[] args ) {
      m( 0 );
   }

   public static void m( int count ) {
      long a, b, c, d, e, f, g, h, i, j, k, l, m;
      System.out.println( count );
      m( ++count );
   }
}

In order to make all variables, including the counter, reside in the stack frames, I decided to pass the count variable to the recursive method by parameter. The only purpose of the 64-bit long variables a to m is to inflate the stack frames.

During its runtime, the program will output the actual counter value on standard output. Sooner or later, the program is going to crash with a stack overflow exception.

When running the program, make sure you redirect the standard error stream

Note that you will have to redirect the standard error stream, to prevent it from interfering with the counter output.

java Demo 2> /dev/null

You will notice a significant difference in the maximum counter value if you comment out the line that declares the long variables a to m.

Using the non-standard option -Xss of the JVM you can change the maximum stack size and explore the influence on the maximum counter value.

java -Xss400k Demo 2> /dev/null

Have fun, and check out my blog entry about the JVM Heap.

Advertisements

About bitjunkie

Teacher, Lecturer, and BITJUNKIE ...
This entry was posted in Java, Programming Essentials and tagged , , , , , . Bookmark the permalink.