简体   繁体   English

try-catch语句中的递归调用

[英]Recursive call in the try-catch statement

I have the following snippet of code: 我有以下代码片段:

public static void main(String[] args) {
    foo();
}
public static void foo() {
    try {
        foo();
    } catch (Throwable t) {
        foo();
    }
}

Can anyone explain me what's going on here? 谁能解释我这是怎么回事? In details, please. 请详细说明。


I have changed this piece and added println methods to show something: 我已经更改了这一部分,并添加了println方法以显示一些内容:

...
try {
    System.out.println("+");
    foo();
} catch (Throwable t) {
    System.out.println("-");
    foo();
}
...

I'm getting something like this (the process hasn't stopped): 我收到这样的消息(过程尚未停止):

+
+
+
+
+--
+--
+
+--
+--
+
+
+--
+--
+
+--
+--
+
+
+
+--
+--

The only way foo can exit is because of stackoverflow. foo可以退出的唯一方法是因为stackoverflow。 We can simulate the effect by 我们可以通过模拟效果

public static void foo(int i)
{
    if(i>=N) return; // stack too deep

    foo(i+1);
    foo(i+1);
}

which is exponentially expensive wrt to the max stack depth. 相对于最大堆叠深度而言,这是指数级的昂贵。

On my machine, the time it takes is about 6ns * 2^N 在我的机器上,所需时间约为6ns * 2^N

The max stack depth is over 10,000, so it will take about 最大堆栈深度超过10,000,因此大约需要

        10000000000000000000000000000000
        .... 
        (thousands of zeros)  
        ... 
        00000000000000000000000000000000 

years to finish the program, give or take a constant factor:) 年完成该计划,给予或采用恒定因子:)

You are calling the same method indefinitely. 您正在无限期地调用相同的方法。 This means the a StackOverflowError will be thrown. 这意味着将引发StackOverflowError。

But because you are catching it ( StackOverflowError is not an exception, it is java.lang.Error, which is a java.lang.Throwable) the application will not stop, it will continue recursing, it will not stop at all. 但是因为您正在捕获它( StackOverflowError也不例外,所以它是java.lang.Error,这是一个java.lang.Throwable),应用程序将不会停止,它将继续递归,也将不会停止。

When I tried to decrease the stack size to the minimum ( -Xss160k -Xoss1k ) it didn't help. 当我尝试将堆栈大小减小到最小( -Xss160k -Xoss1k )时,它没有帮助。

I know I didn't provide an explanation why this happens, I need to profile the code in order to get more information, but this is an interesting issue, maybe someone with deep expertise in JVM internals knows exactly what happened. 我知道我没有提供解释为什么会发生这种情况,我需要分析代码以获取更多信息,但这是一个有趣的问题,也许对JVM内部有很深专业知识的人都知道发生了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM