I have a method to return an HTTP response after a Groovy script is executed. I've created an anonymous thread that is supposed to execute the Groovy script. However, as a precaution, I want the thread to stop after 3 seconds so as to prevent bad scripts (ie: infinite loops) from continuing to run.
public Response runScript(String script) {
GroovyShell shell = new GroovyShell();
Thread thread = new Thread() {
public void run() {
Script validatedScript = shell.parse(script);
validatedScript.run();
}
};
thread.start();
thread.join(3000);
return Response.ok("It ran!", MediaType.TEXT_PLAIN).build();
}
This code works fine for scripts that do not have an infinite loop. However, if there is an infinite loop, the response "It ran!" is delivered to the client, but the thread is still alive. How do I kill this thread after the join()
?