I am using Apache Commons Pool to create a pool of Nashorn engines. On application start I call preparePool()
to warm up the minIdle
number of instances to eval()
all scripts into the engine so that it is ready to answer calls to invokeFunction()
immediately.
The warmup
@Override
public NashornScriptEngine create() {
// ...
try {
engine.eval(asset1);
engine.eval(asset2);
engine.eval(asset3);
} // ...
return engine;
}
Depending on the pool size and the complexity of the preloaded scripts this takes a considerable amount of time.
Questions
Can I warmup only one instance and safely clone it to the number of minIdle
instances?
Could a clone of a created instance be safely serialized and persisted? (which would allow maintaining an engine cache that only needed to be invalidated if one of the assets changes)
Related resources (will update this section when appropriate)
Nashorn's engine instances aren't either cloneable or serializable. I would suggest that you use a single engine instance though and use ScriptEngine.createBindings()
to create multiple Bindings
objects and pool those. You'll obviously need to initialize each Bindings with a call to ScriptEngine.eval(String|Reader, Bindings)
method then. (You can also use ScriptContext
objects instead of just Bindings
; they're practically tuples of bindings and out/err streams.)
The benefit of using a single ScriptEngine
is code sharing. Evaluating the same script into multiple bindings will still only compile the script once (if you use the Compilable
interface) and the code for all function objects will be represented by the same compiled bytecode.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With