Biswa
Biswa

Reputation: 21

How to run two methods in parallel in Groovy?

Example :

def mylist = ['item1','item2']
mylist.each {    
     fun1()
     fun2()
}

def fun1() {
    println "function-1"
}

def fun2() {
    println "function-2"
}

Actual result :

function-1
function-2
function-1
function-2

Expected result :
same as above, however I want fun1() and fun2() to be called in parallel for each item in the list. It does not matter the sequence of output as in my actual code, both methods are independent of each other.

Upvotes: 1

Views: 4151

Answers (1)

tim_yates
tim_yates

Reputation: 171144

As cfrick says, you can use GPars which is now part of groovy:

import static groovyx.gpars.GParsPool.*

def mylist = ['item1','item2']

withPool {
    mylist.eachParallel {    
       fun1()
       fun2()
    }
}

def fun1() {
    println "function-1"
}

def fun2() {
    println "function-2"
}

Upvotes: 3

Related Questions