Home  >  Article  >  Java  >  How to solve the StackOverflowError error problem in Java

How to solve the StackOverflowError error problem in Java

WBOY
WBOYforward
2023-05-13 20:49:043305browse

Introduction to StackOverflowError

StackOverflowError can be annoying to Java developers as it is one of the most common runtime errors we may encounter. In this article, we will learn how this error occurs by looking at various code examples and how to deal with it. How Stack Frames and StackOverflowerError occur Let's start with the basics. When a method is called, a new stack frame is created on the call stack. The stack frame contains the parameters of the called method and its local variables.

StackOverflowError can be annoying to Java developers as it is one of the most common runtime errors we may come across.

In this article, we will understand how this error occurs by looking at various code examples and how to deal with it.

How Stack Frames and StackOverflowerError occur

Let’s start with the basics. When a method is called, a new stack frame is created on the call stack. This stack frame contains the parameters of the called method, its local variables, and the method's return address, which is the point at which method execution should continue after the called method returns.

The creation of stack frames will continue until the end of the method call within the nested method is reached.

During this process, if the JVM encounters a situation where there is no space to create a new stack frame, it will throw a StackOverflower error.

The most common reason why the JVM encounters this is unterminated/infinite recursion - StackOverflowerr's Javadoc description mentions that the error is caused by recursion that is too deep in a specific piece of code.

However, recursion is not the only cause of this error. This can also happen in situations where an application keeps calling methods from within a method until the stack is exhausted. This is a rare situation as no developer would intentionally follow poor coding practices. Another rare reason is a large number of local variables in the method.

StackOverflowError can also be thrown when the application is designed to have cyclic relationships between classes. In this case, each other's constructors are called repeatedly, causing this error. This can also be considered a form of recursion.

Another interesting scenario that causes this error is if a class is instantiated within the same class as an instance variable of that class. This will cause the constructor of the same class to be called again and again (recursively), eventually leading to a stack overflow error.

StackOverflowError running

In the example shown below, due to unexpected recursion, the developer forgot to specify a termination condition for the recursive behavior, a StackOverflowError error will be thrown:

public class UnintendedInfiniteRecursion {
    public int calculateFactorial(int number) {
        return number * calculateFactorial(number - 1);
    }
}

Here, for any value passed into the method, an error is raised in any case:

public class UnintendedInfiniteRecursionManualTest {
    @Test(expected = <a href="https://javakk.com/tag/stackoverflowerror" rel="external nofollow"  rel="external nofollow"      title="查看更多关于 StackOverflowError 的文章" target="_blank">StackOverflowError</a>.class)
    public void givenPositiveIntNoOne_whenCalFact_thenThrowsException() {
        int numToCalcFactorial= 1;
        UnintendedInfiniteRecursion uir 
          = new UnintendedInfiniteRecursion();
        
        uir.calculateFactorial(numToCalcFactorial);
    }
    
    @Test(expected = StackOverflowError.class)
    public void givenPositiveIntGtOne_whenCalcFact_thenThrowsException() {
        int numToCalcFactorial= 2;
        UnintendedInfiniteRecursion uir 
          = new UnintendedInfiniteRecursion();
        
        uir.calculateFactorial(numToCalcFactorial);
    }
    
    @Test(expected = StackOverflowError.class)
    public void givenNegativeInt_whenCalcFact_thenThrowsException() {
        int numToCalcFactorial= -1;
        UnintendedInfiniteRecursion uir 
          = new UnintendedInfiniteRecursion();
        
        uir.calculateFactorial(numToCalcFactorial);
    }
}

However, in the next example, the termination condition is specified, but if the value -1 Passed to the calculateFactorial() method, the termination condition is never met, which results in unterminated/infinite recursion:

public class InfiniteRecursionWithTerminationCondition {
    public int calculateFactorial(int number) {
       return number == 1 ? 1 : number * calculateFactorial(number - 1);
    }
}

This set of tests demonstrates this scenario:

public class InfiniteRecursionWithTerminationConditionManualTest {
    @Test
    public void givenPositiveIntNoOne_whenCalcFact_thenCorrectlyCalc() {
        int numToCalcFactorial = 1;
        InfiniteRecursionWithTerminationCondition irtc 
          = new InfiniteRecursionWithTerminationCondition();

        assertEquals(1, irtc.calculateFactorial(numToCalcFactorial));
    }

    @Test
    public void givenPositiveIntGtOne_whenCalcFact_thenCorrectlyCalc() {
        int numToCalcFactorial = 5;
        InfiniteRecursionWithTerminationCondition irtc 
          = new InfiniteRecursionWithTerminationCondition();

        assertEquals(120, irtc.calculateFactorial(numToCalcFactorial));
    }

    @Test(expected = StackOverflowError.class)
    public void givenNegativeInt_whenCalcFact_thenThrowsException() {
        int numToCalcFactorial = -1;
        InfiniteRecursionWithTerminationCondition irtc 
          = new InfiniteRecursionWithTerminationCondition();

        irtc.calculateFactorial(numToCalcFactorial);
    }
}

In this particular case, if the termination condition is expressed simply as:

public class RecursionWithCorrectTerminationCondition {
    public int calculateFactorial(int number) {
        return number <= 1 ? 1 : number * calculateFactorial(number - 1);
    }
}

The following test shows this situation in practice:

public class RecursionWithCorrectTerminationConditionManualTest {
    @Test
    public void givenNegativeInt_whenCalcFact_thenCorrectlyCalc() {
        int numToCalcFactorial = -1;
        RecursionWithCorrectTerminationCondition rctc 
          = new RecursionWithCorrectTerminationCondition();

        assertEquals(1, rctc.calculateFactorial(numToCalcFactorial));
    }
}

Now let's see A scenario where StackOverflowError error occurs due to circular relationship between classes. Let us consider ClassOne and ClassTwo which instantiate each other in their constructors, thus creating a circular relationship:

public class ClassOne {
    private int oneValue;
    private ClassTwo clsTwoInstance = null;
    
    public ClassOne() {
        oneValue = 0;
        clsTwoInstance = new ClassTwo();
    }
    
    public ClassOne(int oneValue, ClassTwo clsTwoInstance) {
        this.oneValue = oneValue;
        this.clsTwoInstance = clsTwoInstance;
    }
}
public class ClassTwo {
    private int twoValue;
    private ClassOne clsOneInstance = null;
    
    public ClassTwo() {
        twoValue = 10;
        clsOneInstance = new ClassOne();
    }
    
    public ClassTwo(int twoValue, ClassOne clsOneInstance) {
        this.twoValue = twoValue;
        this.clsOneInstance = clsOneInstance;
    }
}

Now let us assume that we try to instantiate ClassOne , as shown in this test:

public class CyclicDependancyManualTest {
    @Test(expected = StackOverflowError.class)
    public void whenInstanciatingClassOne_thenThrowsException() {
        ClassOne obj = new ClassOne();
    }
}

This ultimately results in a StackOverflowError because the constructor of ClassOne instantiates ClassTwo and ClassTwo# The constructor of ## instantiates ClassOne again. This happens repeatedly until it overflows the stack.

Next, we'll look at what happens when a class is instantiated in the same class as an instance variable of that class.

As shown in the next example,

AccountHolder instantiates itself as an instance variable JointaCountHolder:

public class AccountHolder {
    private String firstName;
    private String lastName;
    
    AccountHolder jointAccountHolder = new AccountHolder();
}

When the

AccountHolder class When instantiated, a StackOverflowError error is raised due to recursive calls to the constructor, as shown in this test:

public class AccountHolderManualTest {
    @Test(expected = StackOverflowError.class)
    public void whenInstanciatingAccountHolder_thenThrowsException() {
        AccountHolder holder = new AccountHolder();
    }
}

Solving StackOverflowError

When encountering a StackOverflowError, the best This is done by carefully examining the stack trace to identify repeated patterns of line numbers. This will allow us to locate code with problematic recursion.

Let's examine a few stack traces caused by the code example we saw earlier.

If the expected exception declaration is ignored, this stack trace is generated by

InfiniteCursionWithTerminationConditionManualTest:

java.lang.StackOverflowError
 at c.b.s.InfiniteRecursionWithTerminationCondition
  .calculateFactorial(InfiniteRecursionWithTerminationCondition.java:5)
 at c.b.s.InfiniteRecursionWithTerminationCondition
  .calculateFactorial(InfiniteRecursionWithTerminationCondition.java:5)
 at c.b.s.InfiniteRecursionWithTerminationCondition
  .calculateFactorial(InfiniteRecursionWithTerminationCondition.java:5)
 at c.b.s.InfiniteRecursionWithTerminationCondition
  .calculateFactorial(InfiniteRecursionWithTerminationCondition.java:5)

Here, you can see that line 5 is repeated. This is where the recursive calls are made. Now it's just a matter of checking the code to see if the recursion is done in the correct way.

Here is the stack trace we get by executing

CyclicDependancyManualTest (again, no exception expected):

java.lang.StackOverflowError
  at c.b.s.ClassTwo.<init>(ClassTwo.java:9)
  at c.b.s.ClassOne.<init>(ClassOne.java:9)
  at c.b.s.ClassTwo.<init>(ClassTwo.java:9)
  at c.b.s.ClassOne.<init>(ClassOne.java:9)

该堆栈跟踪显示了在循环关系中的两个类中导致问题的行号。ClassTwo的第9行和ClassOne的第9行指向构造函数中试图实例化另一个类的位置。

彻底检查代码后,如果以下任何一项(或任何其他代码逻辑错误)都不是错误的原因:

  • 错误实现的递归(即没有终止条件)

  • 类之间的循环依赖关系

  • 在同一个类中实例化一个类作为该类的实例变量

尝试增加堆栈大小是个好主意。根据安装的JVM,默认堆栈大小可能会有所不同。

-Xss 标志可以用于从项目的配置或命令行增加堆栈的大小。

The above is the detailed content of How to solve the StackOverflowError error problem in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete