How do I execute two tasks simultaneously and wait for the results in Groovy?

[亡魂溺海] 提交于 2019-11-30 04:55:17

问题


I have a large processing task which I believe is ripe for being made more efficient with concurrency and parallelism.

I had a look at the GPars docs and I found them quite confusing so I hope people here can help.

The first task I would like to do in parallel currently looks like this:

def providerOneProgrammes = providerOneProgrammeService.getProgrammes(timeWindow)
def providerTwoProgrammes = providerTwoProgrammeService.getProgrammes(timeWindow)

both return a list of objects and both can be run in parallel.

I would like to execute them together and then wait for them to finish before processing the return lists (I will then look for matches between the lists but I'll come to that later).

Thanks

Rakesh


回答1:


The simplest way to take advantage of GPars here is with callAsync. Here's a simple example:

@Grab(group='org.codehaus.gpars', module='gpars', version='1.0-beta-2')

import groovyx.gpars.GParsPool

def providerOneProgrammeService(timeWindow) {
    println "p1 starts"
    Thread.sleep(4000)
    println "p1 still going"
    Thread.sleep(4000)
    println "p1 ends"
    return "p1 return value"
}

def providerTwoProgrammeService(timeWindow) {
    println "p2 starts"
    Thread.sleep(5000)
    println "p2 still going"
    Thread.sleep(5000)
    println "p2 still going"
    Thread.sleep(5000)
    println "p2 ends"
    return "p2 return value"
}

def results = []
GParsPool.withPool {
    results << this.&providerOneProgrammeService.callAsync("arg1")
    results << this.&providerTwoProgrammeService.callAsync("arg2")
}
println "done ${results*.get()}"


来源:https://stackoverflow.com/questions/11529521/how-do-i-execute-two-tasks-simultaneously-and-wait-for-the-results-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!