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
- A closure is not automatically safe. It sees the variables of its script, and two threads writing one variable is a race whatever the syntax.
- Order is not guaranteed. A concurrent result is sorted before it is printed, or the page would show a different line on every run.
- GPars is not here. The old Groovy concurrency library adds actors and dataflow; this image has no GPars, and the JDK types cover a script that needs a thread or a pool.
Related
- Java: the concurrency API Groovy uses.
- Closures as arguments: the closure a thread runs.
Автор статьи: Arthur Isaev