Search code examples
javagroovygroovyshell

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


Solution

  • 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