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.
In this Java implementation, we use a ReentrantLock instead of the sync.Mutex from Go. The Container class encapsulates the lock and the map of counters. The inc method uses the lock to ensure thread-safe access to the counters.
In the main method, we create three threads to simulate concurrent access to the container. We use lambda expressions to define the increment operation and create the threads. After starting the threads, we wait for them to finish using the join method.
This example demonstrates how to use locks in Java to safely manage shared state across multiple threads, similar to using mutexes in other languages.