这个问题出现在所有关于GroovyShell的问题的评论中,比如Using GroovyShell as "expression evaluator/engine" (or: How to reuse GroovyShell)。这并不奇怪,因为API的设计似乎根本没有涵盖这个主题。不幸的是,这从来没有明确讨论过。
紧凑形式的问题:
静态初始化:
final GroovyShell shell = new GroovyShell();
final Script thisScript = shell.parse("sleep 1000; return input1+' '+input2");
//anotherScript = // not relevant here but my use-case pre-loads ~300 groovy scripts脚本运行器:
private Object runScript(Script theScript, String param1, String param2) {
theScript.setProperty("input1", param1);
theScript.setProperty("input2", param2);
Object result = theScript.run();
return result;
}序列化执行:
runScript(thisScript, "Hello", "World") -> Hello World
runScript(thisScript, "Guten", "Tag") -> Guten Tag并行执行:
runScript(thisScript, "Hello", "World") -> Guten Tag (!)
runScript(thisScript, "Guten", "Tag") -> Guten Tag问题是绑定(无论是get/setBinding还是setProperty)是在脚本级别完成的。这就像是在通过classLoader加载java.lang.Class对象或修改静态成员变量之后,在该对象上设置一些内容。有没有替代的groovy实现来处理绑定和作为原子操作运行?或者更好:使用上下文对象来执行?
最简单的解决方法是将runScript()同步到脚本对象,但这不能扩展。
发布于 2020-08-18 21:52:10
创建脚本类的不同实例以并行运行它们。
GroovyShell shell = new GroovyShell();
Class<Script> scriptClass = shell.parse("sleep 1000; return input1+' '+input2").getClass();
Object runScript(Class<Script> clazz, String param1, String param2) {
Script theScript = clazz.newInstance();
theScript.setProperty("input1", param1);
theScript.setProperty("input2", param2);
Object result = theScript.run();
return result;
}
//thread test
[
["111","aaa"],
["222","bbb"]
].collect{x->
Thread.start{
println "start $x"
println runScript(scriptClass, x[0], x[1])
}
}*.join()输出:
start [111, aaa]
start [222, bbb]
111 aaa
222 bbbhttps://stackoverflow.com/questions/63465935
复制相似问题