Question

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?

Was it helpful?

Solution 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.

OTHER TIPS

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top