Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    }
    serializeMap(map)

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

like image 235
Sap Avatar asked Aug 09 '11 12:08

Sap


1 Answers

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):

import groovyx.gpars.GParsPool

Map map = [:] as ConcurrentMap

GParsPool.withPool {
  chars.eachParallel { i ->
    def name = getName(i)
    def info = getInfo(i)
    map[name] << info
  }
}
like image 146
Christoph Metzendorf Avatar answered Sep 26 '22 16:09

Christoph Metzendorf