How to perform two tasks at the same time and wait for the results in Groovy?

I have a big processing task, which, it seems to me, has matured to increase efficiency with concurrency and parallelism.

I looked at the GPars docs and I found them quite confusing, so I hope people can help here.

The first task that I would like to do in parallel is as follows:

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

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

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

thanks

Rakesh

+6
source share
1 answer

The easiest way to use GPars here is callAsync . Here is 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()}" 
+14
source

Source: https://habr.com/ru/post/920734/


All Articles