Skip to end of metadata
Go to start of metadata

Using threads and AtomicInteger

From Groovy you can use all of the normal concurrency facilities in Java and combine them with threads and closures as necessary. E.g. a (slightly modified) atomic counter from a Groovy example here:

The output will be something like this:

thread loop 1
main loop 1
thread loop 2
thread loop 3
main loop 2
thread loop 4
thread loop 5
main loop 3
thread loop 6
main loop 4
thread loop 7
thread loop 8

Fibonacci with Executors

A Groovy script to naively calculate the Fibonacci series inspired by the example here.
Note: a version using memoizing will be much more efficient but this illustrates using Java's built-in concurrency primitives from Groovy.

Which produces this:

Calculating Fibonacci sequence in parallel...
n=8 => 21
n=9 => 34
n=10 => 55
n=11 => 89
n=12 => 144
n=13 => 233
n=14 => 377
n=15 => 610
n=16 => 987

If you want to convince yourself that some threads are actually being created, replace the last each line with:

which will add something like the following to your output:

Thread[Reference Handler,10,system]
Thread[Signal Dispatcher,9,system]
Thread[Attach Listener,5,system]
Thread[Java2D Disposer,10,system]

Fibonacci with Functional Java

If you wish to make use of the functionaljava (tested with 2.1.3) library (see the link to the original example), you could use a Groovy program such as this:

Using java.util.concurrent.Exchanger

An example using Exchanger. We have two threads - one keeping evens and exchanging odd values with the other thread. Meanwhile the other thread is working in reverse fashion; keeping the odds and exchanging the evens. The algorithm here is dumb in that it relies on the same number of swaps for each side - which is fine for this example but would need to be altered for more general input values.

Which has the following output:

evens: [2, 22, 4, 24, 6, 26, 8, 28, 10, 30, 12, 32, 14, 34, 16, 36, 18, 38, 20, 40]
odds: [1, 21, 3, 23, 5, 25, 7, 27, 9, 29, 11, 31, 13, 33, 15, 35, 17, 37, 19, 39]

Catching Exceptions with an Exception Handler

When catching Exceptions with an exception handler in Groovy Scripts, there is potential for interaction with Groovy's runtime which catches exceptions and filters stacktraces. The best way to avoid this interaction is to create your own thread and call setDefaultUncaughtExceptionHandler directly on that thread instance as per below:

More Information

See also:

  1. Functional Programming with Groovy
  2. Multithreading with SwingBuilder
  • No labels