简体   繁体   中英

Groovy Shell script object not executed entirely

we are creating a groovy shell object and passing the bindings to the shell then the parsing the groovy code using the shell and initializing a Script object as below

GroovyShell shell = new GroovyShell(binding); 
Script script = shell.parse(//groovy code ); 

then we are storing the script object in a Concurrent hashmap and running the script using script.run() fetching the script from this hashmap , But the groovy code in the script does not executes completely say 1 in 100 runs . we had placed logs in the //groovy code that shows the code did not run completely and neither any exception is thrown

when you run the same instance of Script in different threads at the same time it could be stopped just by logic of your script.

if you want ta cache the parsed script, then store into your map the parsed class and not the instance of script and for each run re-bind variables.

the following code snippet should give you an idea how to do that:

scriptMap = new HashMap()

Script getScript(String code){
    Class<Script> scriptClass = scriptMap.get(code);
    if(scriptClass)return script.newInstance();
    GroovyShell shell = new GroovyShell(); 
    Script script = shell.parse( code );
    scriptMap.put(code, script.getClass());
    return script;
}

Object runScript(String code, Map variables){
    Script script=getScript(code);
    script.setBinding( new Binding(variables) );
    return script.run();
}

println runScript("a+b", [a:2,b:7])
println runScript("(b-a)*3", [a:7,b:9])
println scriptMap

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM