I'm coming from a Java background and I'm stuck learning Groovy and Gradle at the same time, since my purpose for one is the other. :-/ I'm also in need of the GPars stuff since speed and parallelism are an issue. Anyway, I see this GPars example and I have some questions which I think are linguistic nuances, rather than library issues, that I don't yet understand.
//check whether all elements within a collection meet certain criteria
GParsPool.withPool(5) { ForkJoinPool pool ->
assert [1, 2, 3, 4, 5].everyParallel {it > 0}
assert ![1, 2, 3, 4, 5].everyParallel {it > 1}
}
I see ForkJoinPool pool ->..
. Why aren't the two lines wrapped in braces like so. Seems like you would loose track of the scope if it were just an optional omission, like for semicolons:
//check whether all elements within a collection meet certain criteria
GParsPool.withPool(5) { ForkJoinPool pool -> {
assert [1, 2, 3, 4, 5].everyParallel {it > 0}
assert ![1, 2, 3, 4, 5].everyParallel {it > 1}
}
}
What is it
? Is it an iterator? Where did it
come from?
By what means is it possible to call .everyParallel
on an Object when it's never been explicitly wrapped by something that has that function as far as I can tell?
I'll start with the disclaimer that I am by no means a GPars expert, but I have used it in a couple of situations, so hopefully there can be something helpful here (updates from the community are welcome).
Groovy Closures are blocks of code that can be passed around. When a parameter is passed into the block, it will come in before the ->
notation. For example:
GParsPool.withPool(5) { ForkJoinPool pool ->
// Here the `pool` object is available to use for processing.
}
In the case that you do not provide a defined variable, there is an implicit it
object included. The above closure could be written in the following ways:
GParsPool.withPool(5) { Object it ->
// Generically stating that a single object will be passed in, called "it". In this example it is a `ForkJoinPool` object.
}
GParsPool.withPool(5) {
// No "it" object is specified, but you can still use "it" because it is implied.
}
everyParallel()
The GParsPool class enables a ParallelArray-based (from JSR-166y) concurrency DSL for collections and objects. Source
If I understand this correctly, there is functionality automatically added when using GParsPool.withPool()
, which allows you to use methods like everyParallel()
. Dynamic programming FTW! I'm guessing it uses the Groovy metaClass
capability to add methods dynamically at runtime, so that you can call them without adding them yourself.