Parallel with withPool

4.9k Views Asked by At

I found an example on how to use withPool. It says I just need to add the word Parallel to Groovy's methods like collect, find, each, put it into withPool and it executes the code parallel.

import static groovyx.gpars.GParsPool.withPool

list = 1..1000000

withPool{
    squares = list.collectParallel { it * it}
}
println squares

Is there any chance to check if it's really parallel?
I tried a benchmark test with the same code but the sequential way
and the parallel way was much more slowly.

1

There are 1 best solutions below

1
On BEST ANSWER

Not sure what you mean by 'but sequential and the parallel way was much more slowly'...

This will run in parallel, but for this simplistic example, the extra cost of firing off jobs to other processors and handling the ordering of results will probably end up taking longer than just multiplying some numbers

For a simplistic example showing it working, you can do:

import static groovyx.gpars.GParsPool.withPool

list = [ 2, 2, 2, 2, 2 ]

withPool{
    result = list.collectParallel {
        Thread.sleep( it * 1000 )
        it
    }
}
println result

So result should be [2,2,2,2,2], but the collectParallel should finish in less than the 10 seconds you'd expect with the serial collect version

Obviously this depends on you having more than one core ;-)