Skip to content

Instantly share code, notes, and snippets.

@hkondo
Created August 15, 2014 04:45
Show Gist options
  • Select an option

  • Save hkondo/74bf414e68c23461128e to your computer and use it in GitHub Desktop.

Select an option

Save hkondo/74bf414e68c23461128e to your computer and use it in GitHub Desktop.
JavaScript in Java, multiple sessions.
import javax.script.*;
public class Script
{
public static void main(String args[])
{
ScriptEngineManager m = new ScriptEngineManager();
Session s1 = new Session(m);
Session s2 = new Session(m);
try{
s1.eval("x = 10;");
s2.eval("x = 20;");
s1.eval("print('This is s1. The following line should be 10.');");
s1.eval("print(x);");
s2.eval("print('This is s2. The following line should be 20.');");
s2.eval("print(x);");
s1.eval("print('This is s1. The following line should be 10.');");
s1.eval("print(x);");
}catch(ScriptException se){
System.out.println(se);
}finally{
}
}
}
class Session
{
protected ScriptEngine engine;
protected ScriptContext context;
public Session(ScriptEngineManager m)
{
engine = m.getEngineByName("js");
ScriptContext o_context = engine.getContext();
context = new SimpleScriptContext();
// context.setReader(o_context.getReader());
// context.setWriter(o_context.getWriter());
engine.setContext(context);
}
public Object eval(String s) throws ScriptException
{
return engine.eval(s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment