Hello, everyone.
I’m student and I’m studying multi-agent simulation.
So, I expect to use JRuby to describe each agent’s rules.
But I am in trouble using JRuby by Java’s ScriptEngine.
I am trying to use some ScriptEngines that are independent each other.
I expect them to have independent variables, independent methods and
independent constants.
However, I don’t know the way to use them in such situation.
The code that follows to the text shows a sample for my problem.
The code has two ScriptEngines and I expect that they are independent
each other.
But unfortunately, it seems that they share variables and methods.
I use JRuby Ver.1.7.4 and JDK 1.7.0.
Would you please tell me the solution of the problem.
Thank you.
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
/** Test code for ScriptEngine scope*/
public class TestScopeKai {
public static void main(String[] argv){
// Create First ScriptEngine
ScriptEngineManager man=new ScriptEngineManager();
ScriptEngine scriptEngine=man.getEngineByName(“jruby”);
ScriptContext thisContext = scriptEngine.getContext();
Bindings engineScope =
thisContext.getBindings(ScriptContext.ENGINE_SCOPE);
String script=
“CONSTANT=1 \n” + //set 1 to this constant
“def get_constant \n” +
" print ‘in 1st engine, constant value is
‘,CONSTANT,’\n’ \n"+
" return CONSTANT \n"+
“end\n”;
try{
scriptEngine.eval(script, engineScope);
scriptEngine.eval(“get_constant”, engineScope); // It
displays “in 1st engine, constant value is 1” and it’s my expected
result.
}catch(Exception e){
e.printStackTrace();
}
// I hope that second ScriptEngine is independent from the
first one. So, I use new objects.
ScriptEngineManager man2=new ScriptEngineManager();
ScriptEngine scriptEngine2=man2.getEngineByName(“jruby”);
ScriptContext thisContext2 = scriptEngine2.getContext();
Bindings engineScope2 =
thisContext2.getBindings(ScriptContext.ENGINE_SCOPE);
String script2=
“CONSTANT=2 \n” + //set 2 to this constant
“def get_constant2 \n” +
" print ‘in 2nd engine, constant value is
‘,CONSTANT,’\n’ \n"+
" return CONSTANT \n"+
“end\n”;
try{
scriptEngine2.eval(script2, engineScope2); // Warning
“:2 warning: already initialized constant CONSTANT” is appear.
scriptEngine2.eval(“get_constant2”, engineScope2); // It
displays “in 2nd engine, constant value is 2”. Although the result
itself is OK, but the constant has been overwritten.
}catch(Exception e){
e.printStackTrace();
}
// Use the first ScriptEngine again.
try{
scriptEngine.eval(“get_constant”, engineScope); // It
displays “in 1st engine, constant value is 2”. I expected “1”, but it
returns “2”.
scriptEngine.eval(“get_constant2”, engineScope); // It
feels strange that the first engine can call the method that belongs
to the second one.
}catch(Exception e){
e.printStackTrace();
}
}
}
<<>>
in 1st engine, constant value is 1