Concurrent process examples
Concurrent programming is so powerfull with Groovy
Goals
: Intro
Source
: Add comment
import java.util.concurrent.* class ProcessBuilder{ int amount def processes = [] def state void run(){ int startTime = System.currentTimeMillis() def th = Thread.start { try{ (0..<amount).each{ def p = "touch file_${it}".execute() synchronized(processes){ processes.add p } } assert processes.size() == amount processes[processes.size()-1].waitForOrKill(0) state = true }catch(Exception e){ state = false } } th.join() int delayTime = System.currentTimeMillis() - startTime println "Open ${amount} processes in parallel takes ${delayTime}ms, with status: ${state}" } void testOutput(){ (0<amount).each{ assert !new File("file_${it}").exists() } } }
Sample of script to run ProcessBuilder class :
(1..<3).each { // Max thread open int max = 1000 // Increment between test int step = 1 + it // Current number of Threads int i = 100 while(i < max){ def pb = new ProcessBuilder(amount:i) pb.run() pb.testOutput() i += step if(!pb.state) i = max } sleep(10000) pb = null }
:Write output