Why does Java forkcomb not cause stackoverflowerror?
I'm a new programmer. I'm trying to teach myself what causes stackoverflow I play with loops and cause errors, but the forkcomb code I test does not cause errors Why?
public class ForkBomb { public static void main(String[] args) throws java.io.IOException { while(true) { Runtime.getRuntime().exec(new String[]{"java","-cp",System.getProperty("java.class.path"),"ForkBomb"}); } } }
This does not cause a stack overflow Why? However, this leads to a:
public class WhileBomb { public WhileBomb() { while (true) { new WhileBomb(); } } public static void main(String[] args) throws java.io.IOException { WhileBomb goodBye = new WhileBomb(); } }
Solution
Each thread has its own stack When you create a new process, you also get a new thread and a new stack A stack overflow error occurs when filling a single stack, but you create many different stacks, none of which is full
In the second example, you have only one thread and you have a recursive call Each time a method is called, some information is temporarily stored on the stack until the method returns Because your method will never return, the stack will be consumed until you get a stack overflow exception
You don't even need a while loop This also generates a stack overflow exception:
public WhileBomb() { new WhileBomb(); }