The java.lang.StackOverflowError
is a runtime error which points to serious problems that cannot be caught by an application. The java.lang.StackOverflowError
indicates that the application stack is exhausted and is usually caused by deep or infinite recursion.
What Causes java.lang.StackOverflowError in Java
The java.lang.StackOverflowError
occurs when the application stack continues to grow until it reaches the maximum limit. Some of the most common causes for a java.lang.StackOverflowError
are:
- Deep or infinite recursion — If a method calls itself recursively without a terminating condition.
- Cyclic relationships between classes — If a class
A
instantiates an object of classB
, which in turn instantiates an object of classA
. This can be considered as a form of recursion. - Memory intensive applications — Applications that rely on resource heavy objects such as XML documents, GUI or java2D classes.
java.lang.StackOverflowError Example in Java
Here is an example of java.lang.StackOverflowError
thrown due to unintended recursion:
public class StackOverflowErrorExample {
public void print(int myInt) {
System.out.println(myInt);
print(myInt);
}
public static void main(String[] args) {
StackOverflowErrorExample soee = new StackOverflowErrorExample();
soee.print(0);
}
}
In this example, the recursive method print()
calls itself over and over again until it reaches the maximum size of the Java thread stack since a terminating condition is not provided for the recursive calls. When the maximum size of the stack is reached, the program exits with a java.lang.StackOverflowError
:
Exception in thread "main" java.lang.StackOverflowError
at java.base/sun.nio.cs.UTF_8$Encoder.encodeLoop(UTF_8.java:564)
at java.base/java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:585)
at java.base/sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:301)
at java.base/sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:290)
at java.base/sun.nio.cs.StreamEncoder.write(StreamEncoder.java:131)
at java.base/java.io.OutputStreamWriter.write(OutputStreamWriter.java:208)
at java.base/java.io.BufferedWriter.flushBuffer(BufferedWriter.java:120)
at java.base/java.io.PrintStream.writeln(PrintStream.java:722)
at java.base/java.io.PrintStream.println(PrintStream.java:938)
at StackOverflowErrorExample.print(StackOverflowErrorExample.java:3)
at StackOverflowErrorExample.print(StackOverflowErrorExample.java:4)
at StackOverflowErrorExample.print(StackOverflowErrorExample.java:4)
at StackOverflowErrorExample.print(StackOverflowErrorExample.java:4)
at StackOverflowErrorExample.print(StackOverflowErrorExample.java:4)
How to fix java.lang.StackOverflowError in Java
Inspect the stack trace
Carefully inspecting the error stack trace and looking for the repeating pattern of line numbers enables locating the line of code with the recursive calls. When the line is identified, the code should be examined and fixed by specifying a proper terminating condition. As an example, the error stack trace seen earlier can be inspected:
at java.base/java.io.PrintStream.writeln(PrintStream.java:722)
at java.base/java.io.PrintStream.println(PrintStream.java:938)
at StackOverflowErrorExample.print(StackOverflowErrorExample.java:3)
at StackOverflowErrorExample.print(StackOverflowErrorExample.java:4)
at StackOverflowErrorExample.print(StackOverflowErrorExample.java:4)
at StackOverflowErrorExample.print(StackOverflowErrorExample.java:4)
at StackOverflowErrorExample.print(StackOverflowErrorExample.java:4)
In the above trace, line number 4 can be seen repeating, which is where the recursive calls are made and causing java.lang.StackOverflowError
.
Increase Thread Stack Size (-Xss)
If the code has been updated to implement correct recursion and the program still throws a java.lang.StackOverflowError
, the thread stack size can be increased to allow a larger number of invocations. Increasing the stack size can be useful, for example, when the program involves calling a large number of methods or using lots of local variables.
The stack size can be increased by changing the -Xss argument on the JVM, which can be set when starting the application. Here is an example:
-Xss4m
This will set the thread’s stack size to 4 mb which should prevent the JVM from throwing a java.lang.StackOverflowError
.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates Java error monitoring and triaging, making fixing errors easier than ever. Try it today.
This is a typical case of java.lang.StackOverflowError
… The method is recursively calling itself with no exit in doubleValue()
, floatValue()
, etc.
File Rational.java
public class Rational extends Number implements Comparable<Rational> {
private int num;
private int denom;
public Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}
public int compareTo(Rational r) {
if ((num / denom) - (r.num / r.denom) > 0) {
return +1;
} else if ((num / denom) - (r.num / r.denom) < 0) {
return -1;
}
return 0;
}
public Rational add(Rational r) {
return new Rational(num + r.num, denom + r.denom);
}
public Rational sub(Rational r) {
return new Rational(num - r.num, denom - r.denom);
}
public Rational mul(Rational r) {
return new Rational(num * r.num, denom * r.denom);
}
public Rational div(Rational r) {
return new Rational(num * r.denom, denom * r.num);
}
public int gcd(Rational r) {
int i = 1;
while (i != 0) {
i = denom % r.denom;
denom = r.denom;
r.denom = i;
}
return denom;
}
public String toString() {
String a = num + "/" + denom;
return a;
}
public double doubleValue() {
return (double) doubleValue();
}
public float floatValue() {
return (float) floatValue();
}
public int intValue() {
return (int) intValue();
}
public long longValue() {
return (long) longValue();
}
}
File Main.java
public class Main {
public static void main(String[] args) {
Rational a = new Rational(2, 4);
Rational b = new Rational(2, 6);
System.out.println(a + " + " + b + " = " + a.add(b));
System.out.println(a + " - " + b + " = " + a.sub(b));
System.out.println(a + " * " + b + " = " + a.mul(b));
System.out.println(a + " / " + b + " = " + a.div(b));
Rational[] arr = {new Rational(7, 1), new Rational(6, 1),
new Rational(5, 1), new Rational(4, 1),
new Rational(3, 1), new Rational(2, 1),
new Rational(1, 1), new Rational(1, 2),
new Rational(1, 3), new Rational(1, 4),
new Rational(1, 5), new Rational(1, 6),
new Rational(1, 7), new Rational(1, 8),
new Rational(1, 9), new Rational(0, 1)};
selectSort(arr);
for (int i = 0; i < arr.length - 1; ++i) {
if (arr[i].compareTo(arr[i + 1]) > 0) {
System.exit(1);
}
}
Number n = new Rational(3, 2);
System.out.println(n.doubleValue());
System.out.println(n.floatValue());
System.out.println(n.intValue());
System.out.println(n.longValue());
}
public static <T extends Comparable<? super T>> void selectSort(T[] array) {
T temp;
int mini;
for (int i = 0; i < array.length - 1; ++i) {
mini = i;
for (int j = i + 1; j < array.length; ++j) {
if (array[j].compareTo(array[mini]) < 0) {
mini = j;
}
}
if (i != mini) {
temp = array[i];
array[i] = array[mini];
array[mini] = temp;
}
}
}
}
Result
2/4 + 2/6 = 4/10
Exception in thread "main" java.lang.StackOverflowError
2/4 - 2/6 = 0/-2
at com.xetrasu.Rational.doubleValue(Rational.java:64)
2/4 * 2/6 = 4/24
at com.xetrasu.Rational.doubleValue(Rational.java:64)
2/4 / 2/6 = 12/8
at com.xetrasu.Rational.doubleValue(Rational.java:64)
at com.xetrasu.Rational.doubleValue(Rational.java:64)
at com.xetrasu.Rational.doubleValue(Rational.java:64)
at com.xetrasu.Rational.doubleValue(Rational.java:64)
at com.xetrasu.Rational.doubleValue(Rational.java:64)
Here is the source code of StackOverflowError
in OpenJDK 7.
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:
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).
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 |
|
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 |
|
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 |
|
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 |
|
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
, or1MB
. 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
- STACKOVERFLOWERROR: CAUSES & SOLUTIONS
- java.lang.ClassNotFoundException – How to solve Class Not Found Exception
- Unreachable Statement Java Error – How to resolve it
- java.lang.NullPointerException Example – How to handle Java Null Pointer Exception (with video)
- Try Catch Java Example
- Java Stack Example (with video)
- Online Java Compiler – What options are there
- What is null in Java
6. Download the Eclipse Project
This was a tutorial about the StackOverflowError
in Java.
Last updated on Oct. 12th, 2021
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.
Internal Exception: java.lang.StackOverflowError
Hi reddit i have not seen anything like this on the web so i have to ask you what is going on here. I am self hosting a server on java, and while i was exploring the server gave me this Error
Internal Exception: java.lang.StackOverflowError
I tried to allocate default amount, 6Gb, and 2Gb of ram but nothing happens. I will post the crash-report file.When i try to move the server’s world in singleplayer it crashes but with another error and the launcher says something occoured with a village.
I made my friend join far away at our base and nothing happens, the world is perfect, but when i join the server crasher (around 22000 blocks far). Initially the server was made in snapshot 21w42a, then we upgraded and explored on 1.18 pre-1
---- Minecraft Crash Report ---- // But it works on my machine. Time: 11/16/21, 3:51 PM Description: Feature placement java.lang.NullPointerException: Cannot invoke "ddm.a(cao, cps, java.util.Random, gh)" because the return value of "java.util.function.Supplier.get()" is null at dbi.a(SourceFile:75) at dem.a(SourceFile:88) at dem.a(SourceFile:84) at dev.a(SourceFile:62) at cps.a(SourceFile:259) at com.google.common.collect.ImmutableList.forEach(ImmutableList.java:422) at cps.a(SourceFile:258) at cpu.c(SourceFile:134) at cpu.a(SourceFile:274) at acp.a(SourceFile:627) at com.mojang.datafixers.util.Either$Left.map(Either.java:38) at acp.a(SourceFile:621) at java.base/java.util.concurrent.CompletableFuture$UniCompose.tryFire(CompletableFuture.java:1146) at java.base/java.util.concurrent.CompletableFuture$Completion.run(CompletableFuture.java:478) at acr.b(SourceFile:58) at aud.g(SourceFile:91) at aud.a(SourceFile:146) at aud.run(SourceFile:102) at java.base/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1434) at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:295) at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1016) at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1665) at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1598) at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183) A detailed walkthrough of the error, its code path and all known details is as follows: --------------------------------------------------------------------------------------- -- Head -- Thread: Server thread Stacktrace: at dbi.a(SourceFile:75) at dem.a(SourceFile:88) at dem.a(SourceFile:84) at dev.a(SourceFile:62) at cps.a(SourceFile:259) at com.google.common.collect.ImmutableList.forEach(ImmutableList.java:422) -- Feature -- Details: Description: ResourceKey[minecraft:worldgen/structure_feature / minecraft:village] -- Generation -- Details: CenterX: -1243 CenterZ: -359 Seed: -1044045278857617452 Stacktrace: at cps.a(SourceFile:258) at cpu.c(SourceFile:134) at cpu.a(SourceFile:274) -- Chunk to be generated -- Details: Location: -1243,-359 Position hash: -1537598293211 Generator: csx@64962e63 Stacktrace: at acp.a(SourceFile:627) at com.mojang.datafixers.util.Either$Left.map(Either.java:38) at acp.a(SourceFile:621) at java.base/java.util.concurrent.CompletableFuture$UniCompose.tryFire(CompletableFuture.java:1146) at java.base/java.util.concurrent.CompletableFuture$Completion.run(CompletableFuture.java:478) at acr.b(SourceFile:58) at aud.g(SourceFile:91) at aud.a(SourceFile:146) at aud.run(SourceFile:102) -- Affected level -- Details: All players: 1 total; [add['Pax_2004'/172, l='ServerLevel[world]', x=-19937.33, y=73.89, z=-5820.54]] Chunk stats: 3298 Level dimension: minecraft:overworld Level spawn location: World: (-224,68,80), Section: (at 0,4,0 in -14,4,5; chunk contains blocks -224,-64,80 to -209,319,95), Region: (-1,0; contains chunks -32,0 to -1,31, blocks -512,-64,0 to -1,319,511) Level time: 38065462 game time, 5535428 day time Level name: world Level game mode: Game mode: survival (ID 0). Hardcore: false. Cheats: false Level weather: Rain time: 65685 (now: false), thunder time: 58615 (now: false) Known server brands: vanilla Level was modded: false Level storage version: 0x04ABD - Anvil Stacktrace: at net.minecraft.server.MinecraftServer.b(SourceFile:879) at acd.b(SourceFile:326) at net.minecraft.server.MinecraftServer.a(SourceFile:820) at net.minecraft.server.MinecraftServer.w(SourceFile:684) at net.minecraft.server.MinecraftServer.a(SourceFile:270) at java.base/java.lang.Thread.run(Thread.java:831) -- System Details -- Details: Minecraft Version: 1.18 Pre-release 1 Minecraft Version ID: 1.18-pre1 Operating System: Linux (amd64) version 5.14.14-2-default Java Version: 16.0.2, N/A Java VM Version: OpenJDK 64-Bit Server VM (mixed mode), Oracle Corporation Memory: 2704556496 bytes (2579 MiB) / 4034920448 bytes (3848 MiB) up to 4294967296 bytes (4096 MiB) CPUs: 12 Processor Vendor: GenuineIntel Processor Name: Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz Identifier: Intel64 Family 6 Model 158 Stepping 10 Microarchitecture: Coffee Lake Frequency (GHz): 3.20 Number of physical packages: 1 Number of physical CPUs: 6 Number of logical CPUs: 12 Graphics card #0 name: unknown Graphics card #0 vendor: unknown Graphics card #0 VRAM (MB): 0.00 Graphics card #0 deviceId: unknown Graphics card #0 versionInfo: unknown Virtual memory max (MB): 23898.87 Virtual memory used (MB): 9219.66 Swap memory total (MB): 15932.16 Swap memory used (MB): 1.25 JVM Flags: 1 total; -Xmx4G Player Count: 1 / 20; [add['Pax_2004'/172, l='ServerLevel[world]', x=-19937.33, y=73.89, z=-5820.54]] Data Packs: vanilla Is Modded: Probably not. Server jar signature and brand is untouched Type: Dedicated Server (map_server.txt)
Edit: I have more crash-reports
Archived post. New comments cannot be posted and votes cannot be cast.
StackOverFlowError is one of the common confronted JVM error. In this blog post, lets learn inner mechanics of thread stacks, reasons that can trigger StackOverFlowError and potential solutions to address this error.
To gain deeper understanding into StackOverFlowError, 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 = 0f; System.out.println("Hello"); } }
This program is very simple with the following execution code:
- main() method is 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 is 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 above simple program is 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 are executed.
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.