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 actors and message passing.
In this Scala version:
We use ReentrantLock from java.util.concurrent.locks instead of Go’s sync.Mutex.
The Container class encapsulates the lock and the counters.
We use a try-finally block to ensure the lock is always released, similar to Go’s defer.
Instead of goroutines, we use Java threads, which Scala can utilize.
We replace Go’s WaitGroup with explicitly joining the threads at the end.
The doIncrement function is defined as a method returning a Runnable, which is used to create threads.
This example demonstrates how to use mutexes in Scala to safely access shared state from multiple threads, achieving the same goal as the original Go program.