java - 如何避免堆栈溢出错误

标签 java recurrence

我有一个程序可以定义为这样的

reset() {
   //sets all variables to initial values
   //clears all arrays
   method1();
}

method1 (){
    //doSomeStuff;
    method2();
}

method2(){
    //doStuff
    method3();
}

method3(){
    //doStuff
    if (jobDone) reset(); //here the cycle closes
    else method2();
}

所有这些方法的计算量都很大。 根据输入数据和结果,程序可能只执行几个周期并抛出“堆栈溢出”错误。

我更改了 VM 标志 -Xss (-Xss8M),但这并不能真正解决问题。

有什么方法可以让它几乎无限地工作吗?

最佳答案

Luiggi Mendoza 之前提到的解决方案:How to avoid stack overflow error

当你调用reset时,它会调用method1,它会调用method2,它会调用method3,它会调用reset或method2,两者都会导致递归无限循环。

您可能想要:

if (jobDone) return; // here the cycle realy closes

而不是

if (jobDone) reset(); //here the do _not_ close

如果你真的想要无限循环你的代码,这不会因为调用reset或methodi而导致SO:

// assuming jobDone is actually a method, you might need this variable
boolean startReset = true;
while (true) {
        if (startReset) {
            //sets all variables to initial values
            //clears all arrays

            //doSomeStuff from method1;
        }
        //doStuff from method2

        //doStuff
        startReset = jobDone;
    }
}

关于java - 如何避免堆栈溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15734657/

相关文章:

java - 如何根据用户输入创建嵌套的 json 文件?

java - 如何解决组合框的冲突?

java - 如何在java http客户端中使用SSL证书向服务器发出请求

java - 让assertj打印特殊字符?

sql - 如何使用 SQL Server sysschedules 模型查询给定日期的所有事件?

algorithm - 解决: T(n) = T(n-1) + n

algorithm - 子集总和方法总数的递归关系

java - 获取 Unicode 字符近似等于以在 HTML 页面中显示

sharepoint - 从 Sharepoint 日历扩展重复事件不适用于 ViewFields 查询

algorithm - 递归关系,分析算法