Skip to content

Instantly share code, notes, and snippets.

@frankvilhelmsen
Last active December 15, 2015 22:59
Show Gist options
  • Save frankvilhelmsen/5336889 to your computer and use it in GitHub Desktop.
Save frankvilhelmsen/5336889 to your computer and use it in GitHub Desktop.
parallel execution and wrapping jobs in callable groovy tasks
import java.util.concurrent.*
import static java.util.concurrent.TimeUnit.*
long now = System.currentTimeMillis()
// process
NORMAL = 1000; LONG = 2000; LIMIT = 1000
def MAX = 100
def LOW = (MAX * 0.05) // < 5%
def HIGH = (MAX * 0.95) // > 95%
def numbers = []; (1..3).collect{ numbers << Math.random() * MAX }
println "Test has ${numbers.findAll{ e -> e < LOW }.size()} item under low value $LOW and ${numbers.findAll{ e -> e > HIGH}.size()} item over high value $HIGH"
def task = { n ->
t = {
if (n < LOW) { throw new RuntimeException("TIMEOUT LOW")}
if (n > HIGH) { throw new RuntimeException("TIMEOUT HI")}
if (n > LOW && n < HIGH) {sleep(LONG)}
sleep(NORMAL); (n+(n*0.25)); n; } // job in a closure
t as Callable // return block as a callable
}
def workers = []; numbers.each { n -> workers.add(task(n)) }
def executor = Executors.newFixedThreadPool(workers.size());
def futures = executor.invokeAll(workers, LIMIT, SECONDS);
def response = []
try {
for (Future future : futures) {
try {
if (future.isCancelled()) {
response << "Cancelled"
} else {
response << future.get()
}
} catch(Exception e) {
response << e.getMessage()
}
}
} finally {
executor.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!executor.awaitTermination(1, SECONDS)) {
executor.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!executor.awaitTermination(1, SECONDS))
println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
executor.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
println "Set up some response.: $response"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment