java scripting API - how to stop the evaluation

空扰寡人 提交于 2019-12-17 18:32:03

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!