Вопрос

Would the following code eventually throw a StackOverflow error?

public class TestStackOverflow {
    public static void main(String args[]) {
        recursion();
    }
    public static void recursion() {
        try {
            Thread.sleep(100);
        } catch(Exception err) {}
        recursion();
    }
}

It seems that the Thread.sleep(100); prevents the StackOverflow error but I am wondering if overtime a StackOverlow error will be thrown? And why does slowing the recursion prevent it? I guess I am mostly unsure of what a StackOverflow is and why this seems to stop it?

Это было полезно?

Решение 2

Thread.sleep cannot prevent a StackOverflowError. It doesn't take stack frames off the stack. All it will do is postpone the error. Each method calls takes up stack memory. By making a recursive call without stopping, all this program will do is take up more stack memory with each call, eventually filling it up and causing the error.

Taking out Thread.sleep produces the error almost immediately.

Changing it to Thread.sleep(1); (sleep for 1 ms at a time) makes the program take about 11 seconds to produce the error on my machine.

Другие советы

Does Thread.sleep() prevent a StackOverflow error?

No.

Would the following code eventually throw a StackOverflow error?

Yes.

It seems that the Thread.sleep(100); prevents the StackOverflow error

Why?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top