Created
August 9, 2012 17:39
-
-
Save anonymous/3306301 to your computer and use it in GitHub Desktop.
groovy script embedding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import groovy.lang.*; | |
| import org.codehaus.groovy.runtime.InvokerHelper; | |
| import org.codehaus.groovy.control.CompilationFailedException; | |
| import java.util.*; | |
| public class Script { | |
| private static final GroovyClassLoader GCL = new GroovyClassLoader(); // XXX GroovyClassLoader is threadsafe ? | |
| private final Class scriptClass; | |
| public Script(String script) throws CompilationFailedException { | |
| scriptClass = GCL.parseClass(script); | |
| } | |
| public Object invoke(Binding binding) { | |
| groovy.lang.Script gscript = InvokerHelper.createScript(scriptClass, binding); // XXX InvokerHelper.createScript is threadsafe? | |
| return gscript.run(); | |
| } | |
| public static void main(String[] args) throws Exception { | |
| String my_groovy_script_as_string = "(foo, bar) = [bar, foo];"; | |
| final Script script = new Script(my_groovy_script_as_string); | |
| Runnable task = new Runnable() { | |
| public void run() { | |
| Binding binding = new Binding(); | |
| binding.setVariable("foo", UUID.randomUUID().toString()); | |
| binding.setVariable("bar", UUID.randomUUID().toString()); | |
| script.invoke(binding); | |
| } | |
| }; | |
| Thread[] pool = new Thread[] {new Thread(task), new Thread(task), new Thread(task)}; | |
| for (Thread t : pool) t.start(); | |
| for (Thread t : pool) t.join(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment