Skip to content

Instantly share code, notes, and snippets.

@PedroWitzel
Created April 29, 2016 16:18
Show Gist options
  • Save PedroWitzel/cc87745698ddc71512e0ab432abca324 to your computer and use it in GitHub Desktop.
Save PedroWitzel/cc87745698ddc71512e0ab432abca324 to your computer and use it in GitHub Desktop.
gradle - Execute in parallel
#!groovy
/*
* based on http://www.tothenew.com/blog/how-to-use-thread-pooling-using-groovy/
*/
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.Future
// Create a Closure that receives :
// @params -> a list of parameters to be passed to exec_closure
// @executors -> number of executors to use (number of parallel tasks)
// @exec_closure -> the closure to be executed to each one of the params
def exec_parallel = { params, executors, exec_closure ->
def threadPool = Executors.newFixedThreadPool(executors)
try {
List<Future> futures = params.collect { param ->
threadPool.submit({ ->
exec_closure param
} as Callable);
}
// recommended to use following statement to ensure the execution of all tasks.
futures.each { it.get() }
} finally {
threadPool.shutdown()
}
}
// Example
task parallel << {
exec_parallel ([ ['You say', 'goodbye'], ['I say', 'hello'] ], 4) { it1, it2 ->
println "$it1 $it2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment