我有一个程序可以定义为这样的
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/