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.
The easiest is to use GPars which is part of groovy:
import static groovyx.gpars.GParsPool.withPool
withPool {
recordJSON.eachParallel {
do stuff here
}
}
If you are more comfortable with Java thread constructions, this might be of interest (Groovy offers all of the usual Java goodies, with less boilerplate):
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With