问题
i have writen a servlet that recives a java script code and process it and returns the answer. for that i have used the java scripting API
in the code below if script = "print('Hello, World')"; the code will end properly print "hello world". but if script = "while(true);" the script will loop endlessly.
import javax.script.*;
public class EvalScript {
public static void main(String[] args) throws Exception {
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// evaluate JavaScript code from String
engine.eval(script);
}
}
my question is how do i kill the eval process in case it takes too long (lets say 15 sec)?
thanks
回答1:
Run the evaluation in a separate thread and interrupt it after 15s using Thread.interrupt(). This will stop the eval and throw an InterruptedException, which you can catch and return a failure status.
A better solution would be to have some sort of asynch interface to the scripting engine, but as far as I could see this does not exist.
EDIT:
As sfussenegger pointed out, interrupting does not work with the script engine, since it never sleeps or enters any wait state to get interrupted. Niether could I find any periodical callback in the ScriptContext or Bindings objects which could be used as a hook to check for interruptions. There is one method which does work, though : Thread.stop(). It is deprecated and inherently unsafe for a number of reasons, but for completeness I will post my test code here along with Chris Winter
来源:https://stackoverflow.com/questions/1601246/java-scripting-api-how-to-stop-the-evaluation