我的程序使用Java Scripting API可以同时评估一些脚本。它们不使用共享的脚本对象、绑定或上下文,但可以使用相同的ScriptEngine
和CompiledScript
对象。我发现Java 8中的Oracle Nashorn实现不支持多线程,ScriptEngineFactory.getParameter('THREADING')
返回null
,关于这个文档说:
引擎实现不是线程安全的,不能在多个线程上并发地执行脚本。
这是否意味着我应该为每个线程创建一个单独的ScriptEngine
实例?
此外,文档没有提到CompiledScript
的并发使用,但是:
每个CompiledScript都与一个ScriptEngine相关联
可以假定CompiledScript
的线程安全取决于关联的ScriptEngine
,即我应该在Nashorn中为每个线程使用单独的CompiledScript
实例。
如果需要,对于这个(我认为非常常见)情况,什么是合适的解决方案?使用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 (e); }
}
};
threads.start();
}
newBindings()
方法 - 应该是createBindings()
吗? - Szymon