Skip to content

Instantly share code, notes, and snippets.

@purplefox
Created December 10, 2013 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save purplefox/7893408 to your computer and use it in GitHub Desktop.
Save purplefox/7893408 to your computer and use it in GitHub Desktop.
import jdk.nashorn.api.scripting.ScriptUtils;
import javax.script.*;
public class LeakTest {
public static void main(String[] args) {
new LeakTest().run();
}
private String script1 =
"function foo(conf) {\n" +
" java.lang.System.out.println('config.f is ' + conf.f);\n" +
" java.lang.System.out.println('in foo, conf stringified is ' + JSON.stringify(conf));\n" +
"}\n" +
"_javaobject.setFunction(foo);";
private String script2 =
"var conf = {f:'bar'};\n" +
"java.lang.System.out.println('Before call, conf stringified is ' + JSON.stringify(conf));\n" +
"foo(conf);";
private void run() {
try {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("nashorn");
// Run script1 in it's own scope
ScriptContext ctx = new SimpleScriptContext();
Bindings bindings = engine.createBindings();
bindings.put("_javaobject", this);
ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
engine.eval(script1, ctx);
ctx = new SimpleScriptContext();
bindings = engine.createBindings();
bindings.put("foo", fun);
ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
engine.eval(script2, ctx);
} catch (Exception e) {
e.printStackTrace();
}
}
private Object fun;
// This allows us to pass an JavaScript object from one scope to another
public void setFunction(Object function) {
fun = ScriptUtils.wrap(function);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment