I am new to programming, and I’m trying to teach myself what a StackOverflow is caused by. I played around with loops and caused the error, but a code for a forkbomb I tested doesn’t cause the error. Why is this?
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 doesn’t cause a stack overflow. Why? Yet this causes one:
public class WhileBomb
{
public WhileBomb()
{
while (true)
{
new WhileBomb();
}
}
public static void main(String[] args) throws java.io.IOException
{
WhileBomb goodBye = new WhileBomb();
}
}
Each thread gets 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 a single stack is filled, but you are creating many different stacks, none of which ever get full.
In the second example you only have one thread and you have a recursive call. Each time you call a method some information is temporarily stored on the stack until the method returns. Because your method never returns the stack will be consumed until you get a stack overflow exception.
You don’t even need the while loop. This would also give a stack overflow exception: