-1

I was testing a simple infinite recursion application however I do not understand why the output has repeated statement without new lines. It only works correctly if I run the code in the catch block in a new thread.

public class Main{

    private static long count = 0;

    public static void main (String args[]){

        new Main().start();
    }

    public void start(){

        loop();
    }

    public void loop(){

        try{
            loop();

        }catch (StackOverflowError e){

            System.out.println("thread ended (id:" + Thread.currentThread().getId() + ") [count: " +count+"]");
            ++count;
            start();
        }

    }
}

output:

...
thread ended (id:1) [count: 214]thread ended (id:1) [count: 214]thread ended (id:1) [count: 214]thread ended (id:1) [count: 214]thread ended (id:1) [count: 214]
thread ended (id:1) [count: 215]thread ended (id:1) [count: 215]thread ended (id:1) [count: 215]thread ended (id:1) [count: 215]thread ended (id:1) [count: 215]
thread ended (id:1) [count: 216]thread ended (id:1) [count: 216]thread ended (id:1) [count: 216]thread ended (id:1) [count: 216]thread ended (id:1) [count: 216]
...

The amount of repetition varies sometimes there are non (1 statement per line)

Android_Dev
  • 41
  • 1
  • 7

1 Answers1

1

Move the try/catch to start.

public class SO {

    private static long count = 0;

    public static void main(String args[]) {
        new SO().start();
    }

    public void start() {
        try {
            loop();
        } catch (StackOverflowError e) {
            System.out.println("thread ended (id:" + Thread.currentThread().getId() + ") [count: " + count + "]");
            ++count;
            start();
        }
    }

    public void loop() {
        loop();
    }
}

Calling start from deep down a call stack that did not unwind is a bad idea.

Output:

thread ended (id:1) [count: 0]
thread ended (id:1) [count: 1]
thread ended (id:1) [count: 2]
thread ended (id:1) [count: 3]
thread ended (id:1) [count: 4]
thread ended (id:1) [count: 5]
thread ended (id:1) [count: 6]
thread ended (id:1) [count: 7]
thread ended (id:1) [count: 8]
thread ended (id:1) [count: 9]
thread ended (id:1) [count: 10]