exceptions

java.lang.StackOverflowError – How to solve StackOverflowError

The java.lang.stackoverflowerror – StackOverflow Error in Java is thrown to indicate that the application’s stack was exhausted, due to deep recursion.

The StackOverflowError extends the VirtualMachineError class, which indicates that the JVM is broken, or it has run out of resources and cannot operate. Furthermore, the VirtualMachineError extends the Error class, which is used to indicate those serious problems that an application should not catch. A method may not declare such errors in its throw clause, because these errors are abnormal conditions that shall never occur.

Finally, the StackOverflowError exists since the 1.0 version of Java.

You can also check this tutorial in the following video:

java.lang.StackOverflowError – How to solve StackOverflowError – Video

1. The Structure of StackOverflowError

Constructors

  • StackOverflowError()

Creates an instance of the StackOverflowError class, setting null as its message.

  • StackOverflowError(String s)

Creates an instance of the StackOverflowError class, using the specified string as message. The string argument indicates the name of the class that threw the error.

2. The StackOverflowError in Java

When a function 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 StackOverflowError is thrown by the Java Virtual Machine (JVM).

stackoverflow error java - stackoverflowerror

The most common case that can possibly exhaust a Java application’s stack is recursion. In recursion, a method invokes itself during its execution. Recursion is considered as a powerful general-purpose programming technique, but must be used with caution, in order for the StackOverflowError to be avoided.

An example that throws a StackOverflowError is shown below:

StackOverflowErrorExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
public class StackOverflowErrorExample {
     
    public static void recursivePrint(int num) {
        System.out.println("Number: " + num);
         
        if(num == 0)
            return;
        else
            recursivePrint(++num);
    }
     
    public static void main(String[] args) {
        StackOverflowErrorExample.recursivePrint(1);
    }
}

In this example, we define a recursive method, called recursivePrint that prints an integer and then, calls itself, with the next successive integer as an argument. The recursion ends once we invoke the method, passing 0 as a parameter. However, in our example, we start printing numbers from 1 and thus, the recursion will never terminate.

A sample execution, using the -Xss1M flag that specifies the size of the thread stack to equal to 1MB, is shown below:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Number: 1
Number: 2
Number: 3
...
Number: 6262
Number: 6263
Number: 6264
Number: 6265
Number: 6266
Exception in thread "main" java.lang.StackOverflowError
        at java.io.PrintStream.write(PrintStream.java:480)
        at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
        at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
        at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:104)
        at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)
        at java.io.PrintStream.write(PrintStream.java:527)
        at java.io.PrintStream.print(PrintStream.java:669)
        at java.io.PrintStream.println(PrintStream.java:806)
        at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:4)
        at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)
        at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)
        at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)
        ...

Depending on the JVM’s initial configuration, the results may differ, but eventually the StackOverflowError shall be thrown. This example is a very good example of how recursion can cause problems, if not implemented with caution.

3. More about the java.lang.stackoverflowerror

The following example demonstrates the risk of having cyclic relationships between classes:

StackOverflowErrorToStringExample.java:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class A {
    private int aValue;
    private B bInstance = null;
     
    public A() {
        aValue = 0;
        bInstance = new B();
    }
     
    @Override
    public String toString() {
        return "";
    }
}
 
class B {
    private int bValue;
    private A aInstance = null;
     
    public B() {
        bValue = 10;
        aInstance = new A();
    }
     
    @Override
    public String toString() {
        return "";
    }
}
 
public class StackOverflowErrorToStringExample {
    public static void main(String[] args) {
        A obj = new A();
        System.out.println(obj.toString());
    }
}

In this example, we defined two classes, A and B. The class A contains one instance of the B class, while, the B class contains one instance of the A 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 StackOverflowError.

A sample execution is shown below:

1
2
3
4
5
6
7
8
Exception in thread "main" java.lang.StackOverflowError
    at main.java.B.(StackOverflowErrorToStringExample.java:24)
    at main.java.A.(StackOverflowErrorToStringExample.java:9)
    at main.java.B.(StackOverflowErrorToStringExample.java:24)
    at main.java.A.(StackOverflowErrorToStringExample.java:9)
    at main.java.B.(StackOverflowErrorToStringExample.java:24)
    at main.java.A.(StackOverflowErrorToStringExample.java:9)
    ...

4. How to deal with the java.lang.stackoverflowerror

  • The simplest solution is to carefully 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.
  • If you have verified that the recursion is implemented correctly, you can increase the stack’s size, in order to allow a larger number of invocations. Depending on the Java Virtual Machine (JVM) installed, the default thread stack size may equal 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<size>[g|G|m|M|k|K]

5. Additional knowledge

6. Download the Eclipse Project

This was a tutorial about the StackOverflowError in Java.

Download
You can download the full source code of this example here: java.lang.StackOverflowError – How to solve StackOverflowError

Last updated on Oct. 12th, 2021

Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

8 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Harish
Harish
6 years ago

public class Demo
{
Demo obj2=new Demo();
public static void main(String[] args)
{
Demo obj1=new Demo();
}

}

Exception in thread “main” java.lang.StackOverflowError
at Demo.(Demo.java:3)

Morten
Morten
6 years ago

toString is pretty empty, no invokation the corresponding toString in the other class

ch.akhil
ch.akhil
6 years ago

E:\Akhil\classes>javac CmdLine.java
CmdLine.java:10: error: cannot find symbol
for(i=0;i<k.length;i++)
^
symbol: variable i
location: class CmdLine
CmdLine.java:10: error: cannot find symbol
for(i=0;i<k.length;i++)
^
symbol: variable i
location: class CmdLine
CmdLine.java:10: error: cannot find symbol
for(i=0;i

khumbudzo
khumbudzo
6 years ago

how can i ansear yes or no and ask different questions based of respond first time programmer

if (answer.equalsIgnoreCase(“yes”)) {
System.out.println(“are you around ?”);
answer = khumbu.next();
}
if (answer.equalsIgnoreCase(“no”)) {
System.out.println(” were you in town”);
answer = khumbu.next();

}
if (answer.equalsIgnoreCase(“yes”)) {
System.out.println(“are you off tommorow?”);
answer = khumbu.next();

if (answer.equalsIgnoreCase(“yes”)) {
System.out.println(“EAT IT”);
answer = khumbu.next();
}

if (answer.equalsIgnoreCase(“no”)) {
System.out.println(“do you have siblings ?”);
answer = khumbu.next();
}
if (answer.equalsIgnoreCase(“yes”)) {
System.out.println(“name them”);
answer = khumbu.next();
}

Charles John Bhaskar
5 years ago

I have a problem with my website possibly a Java coding error. I am not the developer though. The coding is overflowing on the header. Please give me a step by step correction.

Site: http://www.allbiotechjobs.com

I am running the company all alone now and want to have a head-start now. Any help is much appreciated.

Venu
Venu
4 years ago

I am facing below error while running Jmeter scripts. Hence i am unable to run the scripts. Please help me with the fixes. 2020-03-17 09:11:43,818 ERROR o.a.j.JMeter: Uncaught exception: java.lang.StackOverflowError: null at java.util.Collections$SynchronizedMap.get(Unknown Source) ~[?:1.8.0_221] at org.apache.jmeter.testelement.AbstractTestElement.getProperty(AbstractTestElement.java:184) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.testelement.AbstractTestElement.isEnabled(AbstractTestElement.java:624) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.gui.tree.JMeterTreeNode.isEnabled(JMeterTreeNode.java:66) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.JMeter.convertSubTree(JMeter.java:1046) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.JMeter.convertSubTree(JMeter.java:1058) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.JMeter.convertSubTree(JMeter.java:1064) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.JMeter.convertSubTree(JMeter.java:1058) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.JMeter.convertSubTree(JMeter.java:1064) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.JMeter.convertSubTree(JMeter.java:1058) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.JMeter.convertSubTree(JMeter.java:1064) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.JMeter.convertSubTree(JMeter.java:1058) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.JMeter.convertSubTree(JMeter.java:1064) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.JMeter.convertSubTree(JMeter.java:1058) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.JMeter.convertSubTree(JMeter.java:1064) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.JMeter.convertSubTree(JMeter.java:1058) ~[ApacheJMeter_core.jar:3.3 r1808647] at org.apache.jmeter.JMeter.convertSubTree(JMeter.java:1064) ~[ApacheJMeter_core.jar:3.3 r1808647] at… Read more »

Mike
4 years ago

This was great! Thank you.

Bhagyashri
Bhagyashri
4 years ago

Hi
I need help on how solve simple fix defect using integration

Back to top button