我的程序使用Java Scripting API并且可以同时评估一些脚本.他们不使用共享脚本对象,绑定或上下文,但可以使用相同ScriptEngine和CompiledScript对象.我看到Java 8中的Oracle Nashorn实现不是多线程的,ScriptEngineFactory.getParameter('THREADING')返回null文档所说的内容:
引擎实现不是线程安全的,不能用于在多个线程上并发执行脚本.
这是否意味着我应该ScriptEngine为每个线程创建一个单独的实例?此外,文档没有说明CompiledScript并发使用,但:
每个CompiledScript都与ScriptEngine相关联
可以假设CompiledScript线程安全依赖于相关ScriptEngine,即我应该CompiledScript为Nashorn的每个线程使用单独的实例.
如果我应该,对于这个(我认为非常常见的)案例,使用ThreadLocal,池或其他什么是适当的解决方案?
final String script = "...";
final CompiledScript compiled = ((Compilable)scriptEngine).compile(script);
for (int i=0; i<50; i++) {
Thread thread = new Thread () {
public void run() {
try {
scriptEngine.eval(script, new SimpleBindings ()); //is this code thread-safe?
compiled.eval(new SimpleBindings ()); //and this?
}
catch (Exception e) { throw new RuntimeException …Run Code Online (Sandbox Code Playgroud)