Created
April 29, 2016 16:18
-
-
Save PedroWitzel/cc87745698ddc71512e0ab432abca324 to your computer and use it in GitHub Desktop.
gradle - Execute in parallel
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
#!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