I am using Nashorn via JSR 223 to execute small snippets of user entered script:
public Invocable buildInvocable(String script) throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName(ENGINE);
engine.eval(functions);
engine.eval(script);
return (Invocable) engine;
}
The varying user script calls JavaScript functions that are defined in a static, central library (held in the functions
String in the code snippet above).
Every time I want to get hold of an Invocable
that I can call from my Java I am constantly having to recompile the large library code.
Is there any way to join a previously compiled piece of code in with new code?
Put compiled functions into Bindings like:
If you need you precompile and call JavaSctipt functions with various arguments you may compile them separately and assemble execution flow in Java. With JavaScript engine Nashorn available in Java8 you can do:
You may pass Java objects inside of JavaSctipt, see example with java.util.HashMap above.
Output is:
This is by design of JSR-223;
eval(String)
can't really have a code cache behind it. Well, theoretically it could, but it'd embody a lot of speculation on the part of what the developer wants (and as all speculations, it'd be bound to be wrong some of the time).What you should do is evaluate your
Invocable
once, keep it around and use it repeatedly.When doing so, note that Nashorn does not provide thread safety (JavaScript has no concept of threading, so Nashorn is intentionally not thread safe in order to not have to pay synchronization costs when they aren't mandated by the language semantics). For that reason, your created
Invocable
will not be safe to use from multiple threads with regard to the state of the global variables in the underlying script. (Concurrently running functions that don't interact with the script's global state is fine.)If you need to share it across threads and the functions depend on global state, and the global state can change, then you'll need to add your own scaffolding for that (either synchronization, or resource pooling, or whatever else is currently in fashion for this purpose).