Wednesday, 12 February 2014

How to increase stack size in java

Consider the Below Program

class StackOverFlow{
 static int count = 0;
 static void fun(){
  count++;
  if(count == 100000){
   System.out.println("Count is " + count);
   System.exit(0);
  }
  fun();
 }

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

Above program has a function named fun(), Which will call itself recursively for 100000 times. When I tried to run the above program, I got below error.

Exception in thread "main" java.lang.StackOverflowError
at StackOverFlow.fun(StackOverFlow.java:5)
at StackOverFlow.fun(StackOverFlow.java:8)
at StackOverFlow.fun(StackOverFlow.java:8)
at StackOverFlow.fun(StackOverFlow.java:8)
at StackOverFlow.fun(StackOverFlow.java:8)
at StackOverFlow.fun(StackOverFlow.java:8)
at StackOverFlow.fun(StackOverFlow.java:8)
at StackOverFlow.fun(StackOverFlow.java:8)
at StackOverFlow.fun(StackOverFlow.java:8)
at StackOverFlow.fun(StackOverFlow.java:8)
at StackOverFlow.fun(StackOverFlow.java:8)
at StackOverFlow.fun(StackOverFlow.java:8)
at StackOverFlow.fun(StackOverFlow.java:8)
at StackOverFlow.fun(StackOverFlow.java:8)
at StackOverFlow.fun(StackOverFlow.java:8)

StackOverflowError thrown because an application recurses too deeply.

How to Increase Stack space
Java provides a command line option “-Xss” to increase the thread stack size.

Syntax
-Xss<size>[g|G|m|M|k|K]

Following command runs application with 10MB stack size.

java -Xss10m StackOverFlow

Output
Count is 100000

Remember, Memory is limited, So instead of depending on increasing stack size, focus on your program, find out where it is consuming more stack memory.

The root cause for StackOverflowError is probably recursion

Stack Memory                                                 Heap Memory                                                 Home

No comments:

Post a Comment