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.