I have a certain function in my program that I want to stop on the press of a key. I have a native keyboard hook set up for that purpose. Right now, I call System.exit(0) when that key is detected. However, I don't want to exit the program, just stop that operation and return to where it was called. An example is given below.
public class Main {
public static void main(String[] args) {
System.out.println("Calling function that can be stopped with CTRL+C");
foo(); // Should return when CTRL+C is pressed
System.out.println("Function has returned");
}
}
I've tried putting the call to foo() in a thread so I could call Thread.interrupt()
but I want the function call to be blocking, not non-blocking. Also there are blocking IO calls in foo()
so I'd rather not deal with interrupts unless it's necessary, because I'd have to deal with ClosedByInterruptException
exceptions and that has caused problems before.
Also the body of foo()
is very long and has many function calls inside it, so writing if (stop == true) return;
in the function is not an option.
Is there a better way to do this than making a blocking thread? If so, how? If not, how would I make a blocking thread?