I found an example for fork/join 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 work count and childrenResult?
Why is a 0 passed as a parameter to sum()?
I’m not much familiar with GPars, but the link you provided says it is a Divide-and-Conquer algorithm and clarifies a bit more what’s implicit later on, explaining that
forkOffChild()does not wait — insteadgetChildrenResults()does.You may find easier to understand the provided alternative approach in the same page, that uses a more Java-ish style, if you’re more familiar to that.
childrenResultsresults in calling the methodgetChildrenResults(), this is the “join” in “Fork/Join”, it waits for all children to finish and then returns a list with the results of them (or re-throws any exception a children may have thrown).0is just the initial value for the sum. IfchildrenResultis empty, that’s what gets summed tocount: