Artikel Terbaru

Wednesday, 29 February 2012

Solution for java.lang.StackOverflowError exception in java

StackOverflowError is one of frequent exception/issue in java projects. This exceptions should not be caught by programmer but thrown by java virtual machine at runtime. whenever this exception is thrown, applciation stopped it's execution

java stackoverflowerror class overview:-

StackOverflowError extends java.lang.VirtualMachineError class which inturns extends java.lang.Error. so what is java.lang.Error?. Error class extends Throwable class specifies unusual errors that application unable to catch these exceptions.These exceptions are not programming related exceptions but thrown by java virtual machine.

StackOverflowError exception thrown in the method when the method are called recursively in infinite times.

Let us see the below program how it throws the exceptions

public class StackDemo {

 public static void main(String[] args) {
  StackDemo sd=new StackDemo();

 public void hello(){
output for the above program is exception with message like "Exception in thread "main" java.lang.StackOverflowError" thrown by applications.

The below is the program execution in memory in java vitural machine
1. Main method is starting point for the exectuion in the parent thread called main, once execution starts, main method makes one entry in the bottom of the call stack. please note that each thread has one own call stack.
2. After that,StackDemo Object is created and method hello() is called from the main thread, method area would be stored in the call stack above main () method area.
this method calls hello() method reursively calls same method infinte times, this makes call stack stores all method entires in memory. and size of the call stack is grown and the exception throwns when call stack unable to accomdates enough size for all these entries in memory. here stack is full with all the entries, StackOverflowError is thrown.
3.hello method is called recursively itself infinite times. so please make sure that avoid recursie infinite method calls.

This erros are thrown by java vitural machin, so be causeful with recursive calls in the methods.

Please leave a comment your thoughts on this.