在Java中减少运行时的最大堆栈大小

pvg*_*ijn 3 java stack-overflow runtime

我正在尝试编写一个junit测试来防止一段代码卡在无休止的迭代中,最终会导致StackOverflow.

所以我正在寻找一种方法来减少运行时的堆栈大小,以便Junittest更快地失败.

将max stack设置为jvm参数是不可能的,因为测试是更大的测试套件的一部分.

Jon*_*eet 5

您可以运行一个递归方法,该方法将自己运行给定次数,然后执行给定的操作.听起来很不稳定:(

就像是:

public void eatStackThenExecute(int depth, Runnable action)
{
    // Maybe put some locals here (and use them) to eat more stack per iteration?
    if (depth == 0)
    {
        action();
    }
    else
    {
        eatStackThenExecute(depth - 1, action);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:智能JVM可能会在这里优化尾调用,所以可能是我们需要在递归调用之后执行"某些操作"来阻止它发生...

Ick'n stuff :(