Reusing ScriptContext and Global Variables
Tony Zakula
tonyzakula at gmail.com
Mon Apr 6 13:56:24 UTC 2015
Hello,
We are running scripts server side and using the multi-threaded example
running the same ScriptEngine across multiple threads as per the recent
blog posts and examples here:
https://blogs.oracle.com/nashorn/entry/improving_nashorn_startup_time_using
If I understand the notes below correctly, we can:
1. Seed a ScriptContext.Global_Scope from the Java side with default
variables and values shared between all scripts and threads. These could
never be changed from JavaScript code directly.
2. We would use a new ScriptContext for each request that gets the default
binding and any new bindings we may want to add using the example below.
3. Based on the example and notes in the link, if someone assigned a global
variable with the same name as something in our ScriptContext.Global_Scope,
it would only affect that request ScriptContext and not pollute our default
ScriptContext.
Did I interpret that all correctly?
Another further optimization it seems we could make is to cache and
associate a ScriptContext per user between requests. This would
effectively give us a per user JS engine across multiple requests with very
little overhead it would seem.
Thanks,
Tony
https://wiki.openjdk.java.net/display/Nashorn/Nashorn+jsr223+engine+notes
ScriptContext defCtx = engine.getContext();
defCtx.getBindings(ScriptContext.GLOBAL_SCOPE).put("foo", "hello");
ScriptContext myCtx = new SimpleScriptContext();
myCtx.setBindings(defCtx.getBindings(ScriptContext.ENGINE_SCOPE),
ScriptContext.ENGINE_SCOPE);
Bindings b = new SimpleBindings(); b.put("foo", "world");
myCtx.setBindings(b, ScriptContext.GLOBAL_SCOPE);
More information about the nashorn-dev
mailing list