Unexpected error java lang stackoverflowerror

StackOverflowError is an error which Java doesn t allow to catch for instance stack running out of space as it s one of the most common runtime errors one can encounter. The main cause of the StackOverflowError is that we haven t provided the proper terminating condition to our recursive function or template

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    StackOverflowError is an error which Java doesn’t allow to catch, for instance, stack running out of space, as it’s one of the most common runtime errors one can encounter.

    The main cause of the StackOverflowError is that we haven’t provided the proper terminating condition to our recursive function or template, which means it will turn into an infinite loop.

    When does StackOverflowError encountered?

    When we invoke a method, a new stack frame is created on the call stack or on the thread stack size. This stack frame holds parameters of the invoked method, mostly the local variables and the return address of the method. The creation of these stack frames will be iterative and will be stopped only when the end of the method invokes is found in the nested methods. In amidst of this process, if JVM runs out of space for the new stack frames which are required to be created, it will throw a StackOverflowError.

    For example: Lack of proper or no termination condition. This is mostly the cause of this situation termed as unterminated or infinite recursion.

    Given below is the implementation of infinite recursion:

    public class StackOverflowErrorClass {

        static int i = 0;

        public static int printNumber(int x)

        {

            i = i + 2;

            System.out.println(i);

            return i + printNumber(i + 2);

        }

        public static void main(String[] args)

        {

            StackOverflowErrorClass.printNumber(i);

        }

    }

    Runtime Error:

    RunTime Error in java code :- Exception in thread “main” java.lang.StackOverflowError
    at java.io.PrintStream.write(PrintStream.java:526)
    at java.io.PrintStream.print(PrintStream.java:597)
    at java.io.PrintStream.println(PrintStream.java:736)
    at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:13)
    at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:14)
    at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:14)
    .
    .
    .

    Note: Please run this on your system to see an error thrown, due to the stack size, this may not show error on online IDE.

    How to fix StackOverflowError?

    1. Avoiding repetitive calls: Try to introduce a proper terminating condition or some condition for the recursive calls to ensure that it terminates.

      Given below is the implementation with proper terminating condition:

      public class stackOverflow {

          static int i = 0;

          public static int printNumber(int x)

          {

              i = i + 2;

              System.out.println(i);

              if (i == 10)

                  return i;

              return i + printNumber(i + 2);

          }

          public static void main(String[] args)

          {

              stackOverflow.printNumber(i);

          }

      }

    2. Increasing the Stack Size: The second method could be, if you notice that it’s implemented correctly still we see an error, then we can avoid that only by increasing the Stack Size in order to store the required number of recursive calls. This is achieved by changing the settings of the compiler.

      Cyclic Relationships between classes is the relationship caused when two different classes instantiate each other inside their constructors.

      StackOverflowError is encountered because the constructor of Class A1 is instantiating Class A2, and the constructor of Class A2 is again instantiating Class A1, and it occurs repeatedly until we see StackOverflow. This error is mainly due to the bad calling of constructors, that is, calling each other, which is not even required, and also it doesn’t hold any significance, so we can just avoid introducing them in the codes.

      Given below is the implementation of Cyclic Relationships Between Classes:

      public class A1 {

          public A2 type2;

          public A1()

          {

              type2 = new A2();

          }

          public static void main(String[] args)

          {

              A1 type1 = new A1();

          }

      }

      class A2 {

          public A1 type1;

          public A2()

          {

              type1 = new A1();

          }

      }

      Runtime Error:

      RunTime Error in java code :- Exception in thread “main” java.lang.StackOverflowError
      at A2.(A1.java:32)
      at A1.(A1.java:13)
      at A2.(A1.java:32)
      .
      .
      .

      Note: This will keep repeating, Infinite Recursion is seen by these infinite cyclic calls.

    java.lang.StackOverflowError is sub class of java.lang.VirtualMachineError. JVM throws a stack overflow when application stack exhausted, due to deep recursion.

    What is StackOverFlowError?

    When a method call is invoked by a Java application, a stack frame is allocated on the call stack. The stack frame contains the parameters of the invoked method, its local parameters, and the return address of the method. The return address denotes the execution point from which, the program execution shall continue after the invoked method returns. If there is no space for a new stack frame then, the java.lang.StackOverflowError is thrown by the Java Virtual Machine (JVM).

    Reasons to occurs java.lang.StackOverFlowError

    • Recursion : A method invokes itself during it’s execution and method calling stack reach to max limit of JVMExample 1
    • Circular Dependency on method calling. Example 2

    A method may not declare such errors in its throw clause, because these errors are abnormal conditions that shall never occur.

    Constructors

    • StackOverflowError(): Constructs a StackOverflowError with no detail message.
    • StackOverflowError(String s): Constructs a StackOverflowError with the specified detail message.

    Recusrsion StackOverFlowError Example

    In this below recursion factorial of number example , I have commented out the recursion terminating condition to create StackOverFlowError.

    package com.exceptions.errors;
    
    public class StackOverFlowErrorExample {
    
    	public static void main(String[] args) {
    		RecursionExample recursion=new RecursionExample();
    		System.out.println(recursion.fact(7));
    	}
    }
    
    class RecursionExample
    {
    	public int fact(int n){
    //Uncomment this condition to recursion terminating condition
    //	    if( n == 0 ){
    //	        return 1;
    //	    }
    	    return n * fact(n-1);
    	}
    }
    

    Output

    Exception in thread "main" java.lang.StackOverflowError
    	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
    	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
    	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
    	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
    	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
    	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
    	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
    	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
    	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
    	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
    	at ......
    

    Circular Dependency StackOverFlowError Example

    In this example, we defined two classes, Company and Employee. The class Company contains one instance of the Employee class, while, the Employee class contains one instance of the Company class. Thus, we have a circular dependency between these two classes. Furthermore, each toString() method, invokes the corresponding toString() method of the other class, and so on, which results in a java.lang.StackOverflowError.

    package com.exceptions.errors;
    
    public class StackOverFlowExample2 {
    
    	public static void main(String[] args) {
    		Company company = new Company();
    		System.out.println(company.toString());
    
    	}
    }
    
    class Company {
    	private int budget;
    	private Employee employeeInstance = null;
    
    	public Company() {
    		budget = 0;
    		employeeInstance = new Employee();
    	}
    
    	@Override
    	public String toString() {
    		return "FacingIssueOnIT : Company";
    	}
    }
    
    class Employee {
    	private int salary;
    	private Company companyInstance = null;
    
    	public Employee() {
    		salary = 10;
    		companyInstance = new Company();
    	}
    
    	@Override
    	public String toString() {
    		return "FacingIssueOnIT : Employee";
    	}
    }
    

    Output

    Exception in thread "main" java.lang.StackOverflowError
    	at com.exceptions.errors.Employee.<init>(StackOverFlowExample2.java:33)
    	at com.exceptions.errors.Company.<init>(StackOverFlowExample2.java:18)
    	at com.exceptions.errors.Employee.<init>(StackOverFlowExample2.java:33)
    	at com.exceptions.errors.Company.<init>(StackOverFlowExample2.java:18)
    	at com.exceptions.errors.Employee.<init>(StackOverFlowExample2.java:33)
    	at com.exceptions.errors.Company.<init>(StackOverFlowExample2.java:18)
    	at com.exceptions.errors.Employee.<init>(StackOverFlowExample2.java:33)
    	at com.exceptions.errors.Company.<init>(StackOverFlowExample2.java:18)
    	at com.exceptions.errors.Employee.<init>(StackOverFlowExample2.java:33)
    	at com.exceptions.errors.Company.<init>(StackOverFlowExample2.java:18)
    	at com.exceptions.errors.Employee.<init>
    ....
    

    How to deal with the StackOverflowError

    • In case of recursion, always apply terminating condition and that should execute in some cases so that method call not go to continuous call.
    • To inspect the stack trace and detect the repeating pattern of line numbers. These line numbers indicate the code being recursively called. Once you detect these lines, you must carefully inspect your code and understand why the recursion never terminates.
    • In case recursion and terminating condition are in place correctly.  You can increase the stack’s size, in order to allow a larger number of invocations. Default thread stack configuration depend on JVM some may equals to either 512KB, or 1MB. You can increase the thread stack size using the -Xss flag. This flag can be specified either via the project’s configuration, or via the command line. The format of the -Xss argument is:
       -Xss[g|G|m|M|k|K]

    Know More

    To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:

    • Java Exception Handling Tutorial
    • JDBC : Exception and Warning Handling
    • Mockito Exceptions Handling
    • Java Built-in Exceptions Solutions
    • [Top 50] Exception Handling Interview Question and Answers

    “Learn From Others Experience»

    Introduction

    StackOverFlowError is one of the common JVM error. In this blog post, let’s learn inner mechanics of thread stacks, reasons that can trigger StackOverFlowError and potential solutions to address this error.

    To gain a deeper understanding of this exception, let’s review this simple program:

    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 = 0 f;
      System.out.println("Hello");
     }
    }

    This program is very simple with the following execution code:

    • main() method invoked first
    • main() method invokes a() method. Inside a() method integer variable ‘x’ is initialized to value 0.
    • a() method in turn invokes b() method. Inside b() method Car object constructed and assigned to variable ‘y’.
    • 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 the above simple program 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 got executed.

    thread-stack-frame

    In step #1: main() method pushed into the application thread’s stack. Step #2: a() method pushed into application thread’s stack. In a() method, primitive data type ‘int’ is defined with value 0 and assigned to variable x. This information also pushed into the same stack frame. Note both data i.e. ‘0’ and variable ‘x’ pushed into thread’s stack frame.

    In step #3: b() method pushed into thread’s stack. In b() method, ‘Car’ object created and assigned to variable ‘y’. A crucial point to note here is ‘Car’ object created in the heap and not in the thread’s stack. Only Car object’s reference i.e. y stored in the thread’s stack frame.

    In step #4: c() method pushed into thread’s stack. In c() method, primitive data type ‘float’ is defined with value 0f and assigned to variable z. This information is also pushed into the same stack frame. Note both data i.e. ‘0f’ and variable ‘z’ is pushed into thread’s stack frame.

    thread-stack-frame

    2. StackOverFlowError Cause

    As you can see thread’s stack is storing methods it’s executing, primitive data types, variables, object pointers and return values. All of these consume memory. If thread’s stack sizes grow beyond the allocated memory limit then StackOverflowError is thrown. Let’s look at the below buggy program, which will result in StackOverflowError:

    public class SOFDemo {
    
     public static void a() {
    
      // Buggy line. It will cause method a() to be called infinite number of times.
      a();
     }
    
     public static void main(String args[]) {
    
      a();
     }
    }

    In this program main() method invokes a() method. a() method recursively calls itself. This implementation will cause a() method to be invoked an infinite number of times. In this circumstance, a() method got added to thread’s stack frame an infinite number of times. Thus, after a few thousand iterations thread’s stack size limit might exceeded. Once stack size limit exceeds, it will result in ‘StackOverflowError’:

    Exception in thread "main" java.lang.StackOverflowError
    	at com.buggyapp.stackoverflow.SOFDemo.a(SOFDemo.java:7)
    	at com.buggyapp.stackoverflow.SOFDemo.a(SOFDemo.java:7)
    	at com.buggyapp.stackoverflow.SOFDemo.a(SOFDemo.java:7)
    	at com.buggyapp.stackoverflow.SOFDemo.a(SOFDemo.java:7)
    	at com.buggyapp.stackoverflow.SOFDemo.a(SOFDemo.java:7)
    	at com.buggyapp.stackoverflow.SOFDemo.a(SOFDemo.java:7)
    	at com.buggyapp.stackoverflow.SOFDemo.a(SOFDemo.java:7)
    	at com.buggyapp.stackoverflow.SOFDemo.a(SOFDemo.java:7)
    

    StackOverflowError

    3. Solutions to StackOverflowError

    There are a couple of strategies to address StackOverflowError.

    3.1 Fix the Code

    Because of a non-terminating recursive call (as shown in the above example), threads stack size can grow to a large size. In that circumstance, you must fix the source code which is causing recursive looping. When ‘StackOverflowError’ is thrown, it will print the stacktrace of the code that it was recursively executing. This code is a good pointer to start debugging and fixing the issue. In the above example it’s ‘a()’  method.

    3.2 Increase Thread Stack Size (-Xss)

    There might be a legitimate reason where a threads stack size needs an increment. Maybe thread has to execute a large number of methods or lot of local variables/created in the methods thread has been executing. In such circumstance, you can increase the thread’s stack size using the JVM argument: ‘-Xss’. Pass this argument when you start the application. Example:

    -Xss2m

    This will set the thread’s stack size to 2 Mb. It might bring a question, what is the default thread’s stack size? Default thread stack size varies based on your operating system, java version & vendor.

    JVM version

    Thread stack size

      Sparc 32-bit JVM   

    512k

      Sparc 64-bit JVM  

    1024k

      x86 Solaris/Linux 32-bit JVM

    320K

      x86 Solaris/Linux 64-bit JVM

    1024K

      Windows 32-bit JVM

    320K

      Windows 64-bit JVM

    1024K

    Summary

    In this article, we took a closer look at the StackOverflowError.We got an understanding of the cause of this error along with the options to fix this issue.

    Problem

    Unexpected Error java.lang.StackOverflowError (SCI70534)

    Symptom

    Error in jboss.log:

    ERROR [LogInterceptor] Unexpected
    Error:
    java.lang.StackOverflowError
    ? <<no stack trace
    available>>
    ERROR [JMSContainerInvoker] Exception in JMSCI message
    listener
    javax.ejb.EJBException: Unexpected
    Error
    java.lang.StackOverflowError
    ? <<no stack trace available>>

    Cause

    Due the large number of EDI documents in the file, GIS is building a large
    number of nodes on the DOM tree, which in turn is causing a stack overflow.

    Resolving The Problem

    1. Modify the <SI_DIR>/properties/jboss.properties and jboss.properties.in
    files by changing maxNodesForDOMToXML=-1 to
    maxNodesForDOMToXML=0

    Example:

    # max Nodes before we start
    converting DOM to XML to serialize
    # note this is for serialization only and
    not for db insert.
    # default value = -1. Always use DOM for serialization
    and do not convert to XML.

    #? value = 0. Always use XML for
    serialization and always? convert DOM to XML.
    #? value > 0. Convert DOM to
    XML, total node count is > the number else use
    DOM
    maxNodesForDOMToXML=0

    2. Restart GIS.

    [{«Product»:{«code»:»SS3JSW»,»label»:»IBM Sterling B2B Integrator»},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Component»:»Not Applicable»,»Platform»:[{«code»:»PF025″,»label»:»Platform Independent»}],»Version»:»All»,»Edition»:»»,»Line of Business»:{«code»:»LOB59″,»label»:»Sustainability Software»}}]

    Historical Number

    PRI14363

    Product Synonym

    [<p><b>]Fact[</b><p>];Gentran Integration Suite, Release 3.0 [<br/>] Processing file containing over
    2000 transactions [<br/>] Processing very large file [<br/>] SCI70534

    Понравилась статья? Поделить с друзьями:
  • Unfortunately the installation failed error 0x0005 behringer
  • Unexpected error from external database driver 1
  • Unexpected error during tickets mask data validation перевод
  • Unfortunately an unexpected error occurred and bundler cannot continue
  • Unfortunately an error has occurred перевод