Sunday, February 24, 2008

Groovy power

The concurrent API that was added to Java 5 is very powerful for sumbitting tasks to a worker thread pool, but when you combine it with the Groovy ability to implement single-method interfaces with closures you have a real winner.


import java.util.concurrent.Callable
import java.util.concurrent.Executors

def executorService = Executors.newFixedThreadPool(4)

def x = {
20.times {
println "X"
}
} as Callable

def y = {
20.times {
println " Y"
}
} as Callable

executorService.invokeAll([x, y])

executorService.shutdown()

which of course has an output similar to this:

X
Y
Y
Y
X
Y
X
Y
X
Y
Y
X
X
Y
X
Y
Y
X
X
X

Pretty neat, huh?

No comments: