How to make this simple Groovy code parallel / multithreaded?

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

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

recordJSON.each{ 
    do stuff here
}

Is there a way to execute execution or execute them in parallel? I have done a bit of reading on this topic, but I am a regular encoder and they seem to be a little over my head.

+4
source share
2 answers

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

import static groovyx.gpars.GParsPool.withPool

withPool {
    recordJSON.eachParallel {
        do stuff here
    }
}
+7
source

Java, (Groovy Java- ):

import java.util.concurrent.*
import groovy.json.*

class MyTask implements Runnable {
    File file

    void run() {
        def recordJSON = new JsonSlurper().parseText(file.text)
        println "do stuff here ${file.name}"
    }
}

// ------ main
def pool = Executors.newCachedThreadPool()

(1..6).each {
    def f = new File("f${it}.json")
    pool.submit(new MyTask(file: f))  
}
+1

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


All Articles