My program uses Java Scripting API and can eval some scripts concurrently. They don't use shared script objects, Bindings or Context, but can use same ScriptEngine
and CompiledScript
objects. I see that Oracle Nashorn implementation in Java 8 is not multithreaded, ScriptEngineFactory.getParameter('THREADING')
returns null
about which the documentation says:
The engine implementation is not thread safe, and cannot be used to execute scripts concurrently on multiple threads.
Does it mean that I should create a separate instance of ScriptEngine
for each thread?
Besides, documentation says nothing about CompiledScript
concurrent usage but:
Each CompiledScript is associated with a ScriptEngine
It can be assumed that CompiledScript
thread-safety depends on related ScriptEngine
, i.e. I should use separate CompiledScript
instance for each thread with Nashorn.
If I should, what is the appropriate solution for this (I think very common) case, using ThreadLocal
, a pool or something else?
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();
}