Skip to content

Instantly share code, notes, and snippets.

@jimwhite
Created August 8, 2014 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimwhite/3d15160781911b855796 to your computer and use it in GitHub Desktop.
Save jimwhite/3d15160781911b855796 to your computer and use it in GitHub Desktop.
package groovyx.cli;
import groovy.lang.Binding;
import groovy.lang.MissingPropertyException;
import groovy.lang.Script;
import java.util.HashMap;
import java.util.Map;
/**
* Groovy Script base class that keeps bindings in a ThreadLocal so that scripts can
* be run concurrently without much interference. Note that the class properties of
* the Script object *are* shared, which may or may not be what you want. If you
* don't want that then getProperty/setProperty/invokeMethod also need to be overridden.
*
* @author Jim White (<a href='https://github.com/jimwhite'>https://github.com/jimwhite</a>) on 8/8/14.
*/
abstract public class ThreadLocalScript extends Script {
ThreadLocalScript() { super(new ThreadLocalBinding()); }
public ThreadLocalScript(Binding binding) {
super(new ThreadLocalBinding(binding));
}
@Override
public void setBinding(Binding binding) {
super.setBinding(new ThreadLocalBinding(binding));
}
static class ThreadLocalBinding extends Binding {
ThreadLocal<Map> variables = new ThreadLocal<Map>();
public ThreadLocalBinding() {
variables.set(new HashMap());
}
public ThreadLocalBinding(Binding binding) {
variables.set(binding.getVariables());
}
@Override
public Object getVariable(String name) {
Map map = variables.get();
Object result = map.get(name);
if (result == null && !map.containsKey(name)) {
throw new MissingPropertyException(name, this.getClass());
}
return result;
}
@Override
public boolean hasVariable(String name) {
Map map = variables.get();
return map != null && map.containsKey(name);
}
@Override
public Map getVariables() {
return variables.get();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment