Java ScriptEngineManager share variable between script engines

Description

Java ScriptEngineManager share variable between script engines

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Main {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();

    manager.put("n1", 1);
    manager.put("n2", 2);

    ScriptEngine engine1 = manager.getEngineByName("JavaScript");
    engine1.put("engineName", "Engine-1");

    ScriptEngine engine2 = manager.getEngineByName("JavaScript");
    engine2.put("engineName", "Engine-2");

    String script = "var sum = n1 + n2; print(engineName + ' - Sum = ' + sum)";

    try {/* w  ww.  j  av a2  s  .com*/
      engine1.eval(script);
      engine2.eval(script);

      engine1.put("n2", 10);
      engine2.put("n2", 20);

      engine1.eval(script);
      engine2.eval(script);
    } catch (ScriptException e) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related