Java Reference
In-Depth Information
try {
// Add a variable named msg to the global scope of
// the script
engine.eval("var msg = 'Hello globals'");
// Print the value of the msg value
engine.eval("print(this.msg);");
// Create a ScriptContext and copy the ENGINE_SCOPE
// Bindings of the default
// script context to the new ScriptContext
ScriptContext ctx = new SimpleScriptContext();
ScriptContext defaultCtx = engine.getContext();
Bindings engineBindings = defaultCtx.
getBindings(ENGINE_SCOPE);
ctx.setBindings(engineBindings, ENGINE_SCOPE);
// Use the new ScriptContext to execute the script
engine.eval("print(this.msg);", ctx);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Hello globals
Hello globals
The --global-per-engine option for the Nashorn engine accomplishes the same
things as in the previous example. It shares the script globals among all script contexts.
Listing 12-3 shows how to set this option for the engine. The output confirms that the
engine is using only one copy of globals to execute all scripts.
Listing 12-3. Sharing the Script Globals among All Script Contexts in a Nashorn Engine
// SharedGlobals.java
package com.jdojo.script;
import javax.script.Bindings;
import javax.script.ScriptContext;
import static javax.script.ScriptContext.ENGINE_SCOPE;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleScriptContext;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
Search WWH ::




Custom Search