Sotirios-Efstathios Maneas

About Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a postgraduate student at the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. His main interests include distributed systems, web crawling, model checking, operating systems, programming languages and web applications.

java.lang.StackOverflowError – How to solve StackOverflowError

In this tutorial we will discuss about the StackOverflowError in Java. This error 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 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.

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.

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).

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:

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:

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.

More about the StackOverflowError in Java

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

StackOverflowErrorToStringExample.java:

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:

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)
	...

How to deal with the 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]

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: StackOverflowErrorExample.zip.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close