dscl dscl - 3 months ago 18
Groovy Question

How to make this simple Groovy code concurrent/multi-threaded?

I have a very simple groovy script that works through a JSON and performs some actions. Since there are no dependencies between the JSON records and actions I was hoping I could speed up the execution a bit. Given this codeā€¦

def recordJSON = new JsonSlurper().parseText(myFile.text)

recordJSON.each{
do stuff here
}


Is there a way to thread the execution or perform them in parallel? I've done a bit of reading on the topic, but I'm a casual coder and they seem to be a bit over my head.

Answer

The easiest is to use GPars which is part of groovy:

import static groovyx.gpars.GParsPool.withPool

withPool {
    recordJSON.eachParallel {
        do stuff here
    }
}
Comments