In the previous example we saw how to manage simple counter state using atomic operations. For more complex state we can use a mutex to safely access data across multiple threads.
Running the program shows that the counters updated as expected.
Next we’ll look at implementing this same state management task using only threads and message passing.
In this Groovy example:
We use ReentrantLock instead of sync.Mutex for thread synchronization.
The Container class encapsulates the lock and the counters.
We use a closure doIncrement instead of a function for the incrementing logic.
Groovy’s Thread.start is used to create and start threads, replacing Go’s goroutines.
We use threads*.join() to wait for all threads to complete, which is equivalent to WaitGroup in Go.
The map syntax and string interpolation in Groovy make the code more concise in some places.
This translation maintains the core concepts of the original Go code while adapting to Groovy’s syntax and concurrency model.