1

以下程序应该返回具有空值的行列表。

import groovyx.gpars.GParsPool
import groovyx.gpars.ParallelEnhancer
import org.apache.commons.lang.RandomStringUtils
import groovyx.gprof.*
import static java.lang.Runtime.*;

def rows = []
def list = []

String charset = (('A'..'Z') + ('0'..'9')).join()
Integer length = 9

for (i in 0..1024) {
    rows[i] = RandomStringUtils.random(length, charset.toCharArray())
}

parallelResult = []
// Parallel execution

GParsPool.withPool(8) {
    parallelResult.makeConcurrent()
    rows.eachParallel {
        if (it[0] != null) {
            parallelResult.push(it)
        }
    }
    parallelResult.makeSequential()
}

// Sequential execution 
sequentialResult = []
rows.each {
    if (it[0] != null) {
        sequentialResult.push(it)
    }
}

assert parallelResult.size == sequentialResult.size

有时,结果并不相同。这可能是由于 makeParallel 的一些问题。如果不是 makeParallel,我如何使用 GPars 创建并发列表?

4

1 回答 1

1

我怀疑您已经在 parallelResult 上引入了竞争条件。makeConcurrent() 不会阻止集合上的竞争条件,它只会改变 each()、collect() 和此类方法的行为。

如果要使用累加器保留当前设计,则需要对其进行同步或使用代理。但是,在我看来,您应该考虑使用更实用的方法。也许像“parallelResult = rows.findAllParallel{it[0]!=null}”

于 2015-03-19T08:41:27.867 回答