Search code examples
javajavascriptconcurrencyjava-8nashorn

Does it make sense to load scripts concurrently in Java 8 Nashorn JavaScript engine


Does it make sense to load scripts concurrently in Java 8 Nashorn JavaScript engine for faster startup? Will it rize any problems even if scripts do not modify global variables? I didn't find any information in javax.script.ScriptEngine javadocs.

Moreover, can Nashorn itself load scripts in parallel when engine.eval(...) is called from multiple threads at the same time? Is it safe to do so? If it doesn't, the whole idea of adding parallelism to scripts loading process is doomed.


Solution

  • It may be a good practice to compile your script files (lazily or eagerly) as CompiledScript then eval them.

    Here are example codes: https://github.com/xqbase/util/tree/master/src/main/java/com/xqbase/util/script

    Nashorn is not thread safe, as well as many JS engines like v8. If global variables are thread safe, however, calling CompiledScript.eval() concurrently seems no problems.

    See anther question Java Scripting With Nashorn (JSR 223) & Pre-compilation