StackOverFlowError is one of the common confronted JVM
error. In this blog post lets learn inner mechanics of
thread stacks, reasons that can trigger StackOverFlowError and potential
solutions to address this error.
To gain deeper understanding in to StackOverFlowError,
let's review this simple program:
<<start:code>>
public class SimpleExample {
public static void main(String args[]) {
a();
}
public static void a() {
int x = 0;
b();
}
public static void b() {
Car
y = new Car();
c();
}
public static void c() {
float z = 0f;
System.out.println("Hello");
}
}
<<end:code>>
This program is very simple with following execution
code:
1. main()
method is invoked first
2. main()
method invokes a() method. Inside a() method integer variable ‘x’ is
initialized to value 0.
3. a()
method in turn invokes b() method. Inside b() method Car object is constructed
and assigned to variable ‘y’.
4. b()
method in turn invokes c() method. Inside c() method float variable ‘z’ is
initialized to value 0.
Now let’s review what happens behind the scenes when
above simple program is executed. Each thread in the application has its own
stack. Each stack has multiple stack frames. Thread adds the methods it’s
executing, primitive data types, object pointers, return values to its stack
frame in the sequence order in which they are executed.
Fig 1: Thread's
Stack frame.