Groovy concurrency: the best way to summarize results semantically?

I need to call several methods in parallel and wait for the results. Everyone relies on different resources, so they can return at different times. I need to wait until I get all the results or timeout after a certain time.

I could just create threads with a reference to a shared object using a method call, but is there a better way more groovy for this?

Current implementation:

        Executors exec = Executors.newFixedThreadPool(10);

        for (obj in objects) {
            def method = {
                def result = new ResultObject(a: obj, b: obj.callSomeMethod())
                result
            } as Callable<ResultObject>

            callables << method
        }

        List<Future<ResultObject>> results = exec.invokeAll(callables)

        for (result in results) {
            try{
                 def searchResult = result.get()
                 println 'result retrieved'
            }  catch (Exception e)
            {
                println 'exception'
                e.printStackTrace()
            }
        }
}
+3
source share
2 answers

Groovier GPars - concurrency, Groovy.

import static groovyx.gpars.GParsExecutorsPool.withPool

withPool {
    def callable = {obj -> new ResultObject(a: obj, b: obj.callSomeMethod())}.async()
    List<ResultObject> results = objects.collect(callable)*.get()
}
+6

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


All Articles