I'm trying to set up my java code such that it can be potentially stopped after any point of code execution.
I was thinking of putting all of my code inside a thread and calling Thread.interrupt()
on it when I want it to stop. Note that this method will only cause the code to throw an InterruptedException
if any thread blocking method is being run (Like sleep
, join
, wait
, etc.). Otherwise it will just set the interrupted flag and we have to check it via the isInterrupted()
after every line.
So now all I need to do is insert the following code...
if (myThread.isInterrupted()) {
System.exit(0);
}
after every line of code. If my java code was stored in a String
, how can I insert this line of code after every point of execution of my code?
I was thinking of using the split method on semicolons and inserting the thread code between every element in the resulting array but it doesn't work because, for example, for loops have semicolons that don't represent the end of a statement. I think I would also have to split on closing curly braces too because the also represent the end of a code statement.
EDIT: solution attempt:
final String javaCode = "if (myString.contains(\"foo\")) { return true; } int i = 0;";
final String threadDelimiter = "if (thisThread.isInterrupted()) { System.exit(0); }";
final StringBuffer sb = new StringBuffer();
for (int i = 0; i < javaCode.length(); i++) {
final char currChar = javaCode.charAt(i);
sb.append(currChar);
if ("{};".contains(currChar + "")) {
sb.append(threadDelimiter);
}
}
System.out.println(sb);
This code is almost correct but it would not work for any sort of loops that use semicolon. It also wouldn't work for for loops that don't have braces.