Reusing ScriptContext and Global Variables

Hannes Wallnoefer hannes.wallnoefer at oracle.com
Tue Apr 7 10:22:14 UTC 2015


Hi Tony,

Yes, I think your setup should work.  ScriptEngine.ENGINE_SCOPE is 
equivalent to the JavaScript global object, while GLOBAL_SCOPE can be 
used to provide default values that are shared between JS globals.

Hannes

Am 2015-04-06 um 15:56 schrieb Tony Zakula:
> 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