Atomic Counters in Groovy
In Groovy, we can use the java.util.concurrent.atomic
package to work with atomic counters. Here’s an example that demonstrates the use of atomic counters accessed by multiple threads:
Let’s break down the code and explain its components:
We import
AtomicLong
from thejava.util.concurrent.atomic
package, which provides atomic operations on long values.We also import
CountDownLatch
fromjava.util.concurrent
, which we’ll use to wait for all threads to complete.We create an
AtomicLong
calledops
to represent our counter.We create a
CountDownLatch
initialized with a count of 50, corresponding to the number of threads we’ll create.We use the Groovy
times
method to start 50 threads. Each thread:- Increments the counter 1000 times using
incrementAndGet()
. - Calls
countDown()
on the latch when it’s done.
- Increments the counter 1000 times using
After starting all threads, we call
await()
on the latch to wait for all threads to complete.Finally, we print the value of the counter using
get()
.
When you run this script, you should see:
We expect to get exactly 50,000 operations. If we had used a non-atomic integer and incremented it with regular addition, we’d likely get a different number, changing between runs, because the threads would interfere with each other.
This example demonstrates how to use atomic operations in Groovy to safely manipulate a shared counter from multiple threads. It’s worth noting that while Groovy doesn’t have built-in constructs like goroutines, it can leverage Java’s robust concurrency utilities.
Next, we could explore other concurrency tools available in Groovy and Java, such as locks and synchronized blocks.