Sap Sap - 8 months ago 45
Groovy Question

How to run a loop concurrently in Groovy?

As of now I have code like following in groovy

HashMap map = new HashMap()
for(char i='a'; i<='z'; i++) {
def name = getName(i)
def info getInfo(i)
map.put(name, info)

What is the best way to run this loop concurrently in Groovy?


There's a Groovy extension available called GPars. It supports several concurrency techniques like Fork/Join or the Actor model. Using GPars, your code could look like this (I couldn't figure out exactly what you are iterating over):

Map map = [:] as ConcurrentMap

GParsPool.withPool {
  chars.eachParallel { i ->
    def name = getName(i)
    def info = getInfo(i)
    map[name] << info