Stackoverflow java ошибка

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.

Aren’t there other ways for a stack overflow to occur, not only
through recursion?

Challenge accepted :) StackOverflowError without recursion (challenge failed, see comments):

public class Test
{
    final static int CALLS = 710;

    public static void main(String[] args)
    {
        final Functor[] functors = new Functor[CALLS];
        for (int i = 0; i < CALLS; i++)
        {
            final int finalInt = i;
            functors[i] = new Functor()
            {
                @Override
                public void fun()
                {
                    System.out.print(finalInt + " ");
                    if (finalInt != CALLS - 1)
                    {
                        functors[finalInt + 1].fun();
                    }
                }
            };
        }
        // Let's get ready to ruuuuuuumble!
        functors[0].fun(); // Sorry, couldn't resist to not comment in such moment. 
    }

    interface Functor
    {
        void fun();
    }
}

Compile with standard javac Test.java and run with java -Xss104k Test 2> out. After that, more out will tell you:

Exception in thread "main" java.lang.StackOverflowError

Second try.

Now the idea is even simpler. Primitives in Java can be stored on the stack. So, let’s declare a lot of doubles, like double a1,a2,a3.... This script can write, compile and run the code for us:

#!/bin/sh

VARIABLES=4000
NAME=Test
FILE=$NAME.java
SOURCE="public class $NAME{public static void main(String[] args){double "
for i in $(seq 1 $VARIABLES);
do
    SOURCE=$SOURCE"a$i,"
done
SOURCE=$SOURCE"b=0;System.out.println(b);}}"
echo $SOURCE > $FILE
javac $FILE
java -Xss104k $NAME

And… I got something unexpected:

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007f4822f9d501, pid=4988, tid=139947823249152
#
# JRE version: 6.0_27-b27
# Java VM: OpenJDK 64-Bit Server VM (20.0-b12 mixed mode linux-amd64 compressed oops)
# Derivative: IcedTea6 1.12.6
# Distribution: Ubuntu 10.04.1 LTS, package 6b27-1.12.6-1ubuntu0.10.04.2
# Problematic frame:
# V  [libjvm.so+0x4ce501]  JavaThread::last_frame()+0xa1
#
# An error report file with more information is saved as:
# /home/adam/Desktop/test/hs_err_pid4988.log
#
# If you would like to submit a bug report, please include
# instructions how to reproduce the bug and visit:
#   https://bugs.launchpad.net/ubuntu/+source/openjdk-6/
#
Aborted

It’s 100% repetitive. This is related to your second question:

Does the StackOverflowError happen before the JVM actually overflows
the stack or after?

So, in case of OpenJDK 20.0-b12 we can see that JVM firstly exploded. But it seems like a bug, maybe someone can confirm that in comments please, because I’m not sure. Should I report this? Maybe it’s already fixed in some newer version… According to JVM specification link (given by JB Nizet in a comment) JVM should throw a StackOverflowError, not die:

If the computation in a thread requires a larger Java Virtual Machine
stack than is permitted, the Java Virtual Machine throws a
StackOverflowError.


Third try.

public class Test {
    Test test = new Test();

    public static void main(String[] args) {
        new Test();
    }
}

We want to create new Test object. So, its (implicit) constructor will be called. But, just before that, all the members of Test are initialized. So, Test test = new Test() is executed first…

We want to create new Test object…

Update: Bad luck, this is recursion, I asked question about that here.

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.

Last Updated :
07 Apr, 2020

Like Article

Save Article

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:

  1. Deep or infinite recursion — If a method calls itself recursively without a terminating condition.
  2. Cyclic relationships between classes — If a class A instantiates an object of class B, which in turn instantiates an object of class A. This can be considered as a form of recursion.
  3. 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

Rollbar in action

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.

Автор оригинала: baeldung.

1. Обзор

StackOverflowError может раздражать разработчиков Java, так как это одна из самых распространенных ошибок во время выполнения, с которой мы можем столкнуться.

В этой статье мы рассмотрим, как может возникнуть эта ошибка, рассмотрев различные примеры кода, а также то, как мы можем с ней справиться.

Давайте начнем с основ. При вызове метода в стеке вызовов создается новый кадр стека. Этот кадр стека содержит параметры вызываемого метода, его локальные переменные и адрес возврата метода, т. е. точку, из которой выполнение метода должно продолжаться после возврата вызванного метода.

Создание фреймов стека будет продолжаться до тех пор, пока не будет достигнут конец вызовов методов, найденных внутри вложенных методов.

Во время этого процесса, если JVM столкнется с ситуацией, когда нет места для создания нового кадра стека, он выдаст StackOverflowError .

Наиболее распространенной причиной, по которой JVM сталкивается с этой ситуацией, является unterminated/бесконечная рекурсия – в описании Javadoc для StackOverflowError упоминается, что ошибка возникает в результате слишком глубокой рекурсии в конкретном фрагменте кода.

Однако рекурсия-не единственная причина этой ошибки. Это также может произойти в ситуации, когда приложение продолжает вызывать методы из методов до тех пор, пока стек не будет исчерпан . Это редкий случай, поскольку ни один разработчик не будет намеренно следовать плохим методам кодирования. Другой редкой причиной является наличие огромного количества локальных переменных внутри метода .

Ошибка StackOverflowError также может быть вызвана, когда приложение предназначено для циклических отношений c между классами . В этой ситуации конструкторы друг друга вызываются повторно, что приводит к возникновению этой ошибки. Это также можно рассматривать как форму рекурсии.

Другой интересный сценарий, который вызывает эту ошибку, заключается в том, что экземпляр класса создается в том же классе, что и переменная экземпляра этого класса . Это приведет к тому, что конструктор одного и того же класса будет вызываться снова и снова (рекурсивно), что в конечном итоге приведет к ошибке StackOverflowError.

В следующем разделе мы рассмотрим некоторые примеры кода, демонстрирующие эти сценарии.

3. Ошибка StackOverflowError в действии

В примере, показанном ниже, StackOverflowError будет вызван из-за непреднамеренной рекурсии, когда разработчик забыл указать условие завершения для рекурсивного поведения:

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

Здесь ошибка возникает во всех случаях для любого значения, переданного в метод:

public class UnintendedInfiniteRecursionManualTest {
    @Test(expected = StackOverflowError.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);
    }
}

Однако в следующем примере указано условие завершения, но оно никогда не выполняется, если значение -1 передается в метод calculateFactorial () , который вызывает нескончаемую/бесконечную рекурсию:

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

Этот набор тестов демонстрирует этот сценарий:

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);
    }
}

В данном конкретном случае ошибки можно было бы полностью избежать, если бы условие завершения было просто сформулировано как:

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

Вот тест, который показывает этот сценарий на практике:

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

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

Теперь давайте рассмотрим сценарий, в котором StackOverflowError возникает в результате циклических отношений между классами. Давайте рассмотрим ClassOne и classstwo , которые создают экземпляры друг друга внутри своих конструкторов, вызывая циклическую связь:

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;
    }
}

Теперь предположим, что мы попытаемся создать экземпляр Class One , как показано в этом тесте:

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

Это заканчивается StackOverflowError , так как конструктор Class One создает экземпляр Class Two, и конструктор classwo снова создает экземпляр ClassOne. И это повторяется до тех пор, пока он не переполнит стек.

Далее мы рассмотрим, что происходит, когда экземпляр класса создается в том же классе, что и переменная экземпляра этого класса.

Как видно из следующего примера, Владелец счета создает экземпляр в качестве переменной экземпляра Владелец совместного счета :

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

Когда Владелец учетной записи класс создается , a StackOverflowError выбрасывается из-за рекурсивного вызова конструктора, как показано в этом тесте:

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

4. Работа С Ошибкой StackOverflowError

Лучшее, что можно сделать при обнаружении StackOverflowError , – это осторожно проверить трассировку стека, чтобы определить повторяющийся шаблон номеров строк. Это позволит нам найти код, который имеет проблемную рекурсию.

Лучшее, что можно сделать при обнаружении || StackOverflowError||, – это осторожно проверить трассировку стека, чтобы определить повторяющийся шаблон номеров строк. Это позволит нам найти код, который имеет проблемную рекурсию.

Эта трассировка стека создается Бесконечной рекурсией С ручным тестом условия завершения , если мы опустим объявление ожидаемого исключения:

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)

Здесь можно увидеть повторение строки № 5. Именно здесь выполняется рекурсивный вызов. Теперь это просто вопрос изучения кода, чтобы увидеть, правильно ли выполняется рекурсия.

Вот трассировка стека, которую мы получаем, выполняя ручной тест циклической зависимости (опять же, без ожидаемого исключения):

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

Эта трассировка стека показывает номера строк, которые вызывают проблему в двух классах, находящихся в циклической связи. Строка номер 9 класса Два и строка номер 9 класса Один указывают на местоположение внутри конструктора, где он пытается создать экземпляр другого класса.

После тщательной проверки кода и если ни одно из следующих действий (или любая другая логическая ошибка кода) не является причиной ошибки:

  • Неправильно реализованная рекурсия (т. е. без условия завершения)
  • Циклическая зависимость между классами
  • Создание экземпляра класса в том же классе, что и переменная экземпляра этого класса

Было бы неплохо попытаться увеличить размер стека. В зависимости от установленной JVM размер стека по умолчанию может варьироваться.

Флаг -Xss можно использовать для увеличения размера стека либо из конфигурации проекта, либо из командной строки.

5. Заключение

В этой статье мы более подробно рассмотрели StackOverflowError , включая то, как Java-код может вызвать его, а также как мы можем диагностировать и исправить его.

Исходный код, связанный с этой статьей, можно найти на GitHub .

Понравилась статья? Поделить с друзьями:
  • Ssangyong actyon ошибка p1254 ssangyong
  • Ssangyong kyron ошибка p2222
  • Ssangyong actyon ошибка p0172
  • Srttrail код ошибки 0x0
  • Stackhash ошибка cyberpunk 2077