Example of plug / attach to GPars

I found a fork / join example in GPars here: Fork / Join

import static groovyx.gpars.GParsPool.runForkJoin
import static groovyx.gpars.GParsPool.withPool
withPool() {
    println """Number of files: ${
        runForkJoin(new File("./src")) {file ->
            long count = 0
            file.eachFile {
                if (it.isDirectory()) {
                    println "Forking a child task for $it"
                    forkOffChild(it)           //fork a child task
                } else {
                    count++
                }
            }
            return count + (childrenResults.sum(0))
            //use results of children tasks to calculate and store own result
        }
    }"""
}

      

It works and returns the correct number of files, but unfortunately I don't understand this line:

return count + (childrenResults.sum(0))

      

How exactly do count

and work childrenResult

?
Why 0

is it passed as a parameter sum()

?

+3


source to share


1 answer


I'm not very familiar with GPars, but the link you gave says it is a Divide-and-Conquer algorithm and elaborates a bit more of what is later implied by explaining what forkOffChild()

does not wait - getChildrenResults()

does instead .

You may find it easier to understand the provided alternative approach on the same page that uses a more Java-ish style if you are more familiar with it.

childrenResults

results in a method call getChildrenResults()

, this is "join" in "Fork / Join", it waits for all children to finish, and then returns a list with the results from them (or rethrows any exception that the children might throw).



0

is just the initial value for the amount. If childrenResult

empty, then what is added to count

:

groovy:000> [].sum(1)
===> 1
groovy:000> [1].sum(1)
===> 2

      

+3


source







All Articles