Caching and re-using bindings

Edmond Kemokai ekemokai at gmail.com
Mon Dec 5 20:01:56 UTC 2016


Why don't you create instances of SimpleBinding and use those as needed?
Use ScriptEngine.setBindings to reset the binding...

On Dec 5, 2016 1:36 PM, "yikes aroni" <yikesaroni at gmail.com> wrote:

> I want to cache ScriptEngine bindings for reuse. The basic algo would be
>
> 1) Build up my ScriptEngine (SE) with stuff i need.
> 2) Snapshot the bindings -- i.e., cache them
> Use engine.getBindings(ScriptContext.ENGINE_SCOPE)
> 3) Use the SE for stuff that might modify its state.
> 4) When done, replace the SE's bindings with my snapshotted bindings
> Use engine.setBindings(_bindings_, ScriptContext.ENGINE_SCOPE)
> 5) I now have a "fresh" SE to use.
>
> The problem is that this doesn't work as expected. The cached bindings
> appear to point to the actual SE bindings and therefore whatever gets added
> to the SE bindings, also gets added to the cached bindings. Here's some
> code to show how it's not doing what i would expect.
>
> public class TempEngineTest {
>
> static ScriptEngineManager seManager = new ScriptEngineManager();
> static ScriptEngine se = seManager.getEngineByName("nashorn");
> public static void printBindings(Map<String, Object> bindings) {
> for (Map.Entry<String, Object> entry : bindings.entrySet()) {
>    System.out.println(entry.getKey() + " = " + entry.getValue());
> }
> }
> public static void main(String[] a) throws Exception {
> // put variable globalA into the ScriptContext.ENGINE_SCOPE bindings
> se.eval("globalA = 'testA';");
> // Snapshot the bindings from the engine.
> Bindings bEngine = se.getBindings(ScriptContext.ENGINE_SCOPE );
> // print the bindings to confirm there is only one variable in them. -->
> TRUE
> printBindings(bEngine);
> // put variable globalB into the ScriptContext.ENGINE_SCOPE bindings
> se.eval("globalB = 'testB';");
> // print the bindings. Now both variables are present........... WHY???
> printBindings(bEngine);
> }
> }
>
> I've seen suggestions to cache and reuse bindings in various articles, but
> no specific code for doing so. How do i accomplish this in actual code?
>
> thanks
>


More information about the nashorn-dev mailing list