Reputation: 31
Sorry, for probably a dumb question, I'm new to Java.
Is there a way to make an endless recursion in Java, somithing like:
public void sillyMethod()
{
System.out.println(i);
i++;
sillyMethod();
}
it throws StackOverflowError, but I really want to run it endless. Is there any way to make it?
Thanks!
Upvotes: 3
Views: 1971
Reputation: 6536
With Java, you cannot do this. However, tail call optimization in languages (esp. functional ones such as Ocaml), you can do this since it internally turns it into a loop.
Upvotes: 0
Reputation: 420951
Yes and no, (but mostly no! :)
No, it's not possible (the most sensible answer):
For every call, there will be an activation record pushed onto the JVM call stack. This takes a non-zero amount of memory, thus you will at some point run out of memory, at which point a StackOverflowException will be thrown.
Yes, it is possible (the super-theoretical answer):
There is nothing in the Java Language Specification that explicitly says that you should eventually run into a StackOverflowException. This means that if you find a cleaver enough compiler, it may be intelligent enough to compile this into a loop.
A related question would be, "Does the JVM support tail-call optimization." The answer to this question is, "no, not at moment, but it's not ruled out for future versions".
Upvotes: 5
Reputation: 3068
As others above have said, infinite recursion will eventually lead to a stack overflow, at least as far as the JVM implementation is concerned.
You could do something like this, which is similar, but avoids the stack expansion by spawning a new thread right before the old one dies.
public class SillyClass implements Runnable {
private final int count;
public SillyClass(int cnt) {
this.count = cnt;
}
public static void main(String[] args) {
Thread t = new Thread(new SillyClass(0));
t.start();
}
@Override
public void run() {
System.out.println(count);
Thread t = new Thread(new SillyClass(count + 1));
t.start();
}
}
Upvotes: 1
Reputation: 64
Not recursively, no. It does imply creating an ever-increasing call stack, and eventually you will run out of memory to contain it.
Upvotes: 0