Concurrency with the JDK

Groovy has no concurrency API of its own: a Groovy thread is a java.lang.Thread, and a pool is an ExecutorService of the JDK. The closure syntax makes both shorter, and the rules are the ones of Java.

A thread per task

threads.groovy

import java.util.concurrent.ConcurrentLinkedQueue def results = new ConcurrentLinkedQueue<Integer>() def threads = (1..3).collect { int n -> Thread.start { results << n * n } } threads*.join() println results.toList().sort()

groovy threads.groovy

[1, 4, 9]

Thread.start { } starts a thread whose body is the closure, and join() waits for it. The order the three threads finish in changes between runs, so the results go into a concurrent queue and the page sorts them before it prints: a shared ArrayList would also lose writes, because two threads appending at once is a data race.

A pool of executors

pool.groovy

import java.util.concurrent.Callable import java.util.concurrent.Executors def pool = Executors.newFixedThreadPool(2) def futures = (1..4).collect { int n -> pool.submit({ -> n * 10 } as Callable) } println futures*.get().sort() pool.shutdown()

groovy pool.groovy

[10, 20, 30, 40]

The pool reuses two threads for four tasks, and each submit returns a Future. get() waits for the result, so the four values are available before the list is printed. shutdown() lets the pool finish and ends its threads, which a program that exits must call or its JVM keeps running.

What stays the same

Related

Article author: Arthur Isaev