ConcurrentException/NullPointerException in GParsPool runForkJoin
For a little context, i'm trying to solve Project Euler problem 31 using excellent GParsPool Fork/Join support.
For that, i've written the foolowing code :
import groovyx.gpars.*
import groovy.util.GroovyCollections
@Grab(group="org.codehaus.gpars", module="gpars", version="0.11")
def getMatchingCombos(target) {
combos = [200开发者_开发问答, 100 /*, 50, 20, 10, 5, 2, 1*/]
GParsPool.withPool(1) { pool ->
combos = combos.collectParallel { n ->
((0..(target/n)).step(1) as TreeSet).collect { p -> p*n }
}
return GParsPool.runForkJoin(combos, 0, 0, target) { usableCombos, comboIndex, sum, targetSum ->
def offset = "\t"*comboIndex
def results = 0
if(sum<=targetSum) {
if(comboIndex<combos.size()) {
usableCombos[comboIndex].each { n ->
println offset+"now trying with $comboIndex element value $n (curent sum is $sum)"
results += forkOffChild(usableCombos, comboIndex+1, sum+n, targetSum)
}
} else {
if(sum==targetSum) {
results +=1
println offset+"sum is target ! so we have $results"
}
}
}
return results;
}
}
}
println getMatchingCombos(200)
Unfortunatly, each time I try to run this, I get the following stack trace :
now trying with 0 element value 0 (curent sum is 0). Known combos are [[0, 200], [0, 100, 200]] and target is 200
now trying with 1 element value 0 (curent sum is 0). Known combos are [[0, 200], [0, 100, 200]] and target is 20
0
Caught: java.util.concurrent.ExecutionException: java.lang.NullPointerException
at groovyx.gpars.GParsPool.runForkJoin(GParsPool.groovy:305)
at probleme_31$_getMatchingCombos_closure1.doCall(probleme_31.groovy:18)
at groovyx.gpars.GParsPool$_withExistingPool_closure1.doCall(GParsPool.groovy:170)
at groovyx.gpars.GParsPool$_withExistingPool_closure1.doCall(GParsPool.groovy)
at groovyx.gpars.GParsPool.withExistingPool(GParsPool.groovy:169)
at groovyx.gpars.GParsPool.withPool(GParsPool.groovy:141)
at groovyx.gpars.GParsPool.withPool(GParsPool.groovy:117)
at probleme_31.getMatchingCombos(probleme_31.groovy:9)
at probleme_31.run(probleme_31.groovy:41)
I understand it has something to do with the way i want to exploit Fork/Join as a recursion "flattening" mechanism, but what is the error I'm doing here ?
You're incorrectly trying to read the children results as a return value from the forkOffChild() method, while this should be done using getChildrenResults().
return GParsPool.runForkJoin(combos, 0, 0, target) { usableCombos, comboIndex, sum, targetSum ->
def offset = "\t"*comboIndex
def results = 0
if(sum<=targetSum) {
if(comboIndex<combos.size()) {
usableCombos[comboIndex].each { n ->
println offset+"now trying with $comboIndex element value $n (curent sum is $sum)"
forkOffChild(usableCombos, comboIndex+1, sum+n, targetSum)
}
} else {
if(sum==targetSum) {
results +=1
println offset+"sum is target ! so we have $results"
}
}
}
results += getChildrenResults().sum(0)
return results;
}
精彩评论