How to interrupt an Infinite Loop

big zero picture big zero · Aug 17, 2012 · Viewed 12k times · Source

Though I know it'll be a bit silly to ask, still I want to inquire more about the technical perspective of it.

A simple example of an infinite loop:

public class LoopInfinite {
    public static void main(String[] args) {
        for (;;) {
            System.out.println("Stack Overflow");
        }
    }
}

How can I interrupt (stop) this infinite loop from outside of this class (e.g., with the help of inheritance)?

Answer

David Grant picture David Grant · Aug 17, 2012

I feel dirty even writing this, but...

From a different thread, you could call System.setOut() with a PrintStream implementation, which throws a RuntimeException when you call println().