In this example, we use Java’s concurrency features to manage shared state across multiple threads. This approach aligns with the idea of sharing memory by communicating and having each piece of data owned by exactly one thread.
The ReadOp and WriteOp classes encapsulate read and write requests, along with a way for the owning thread to respond.
We create a single thread that owns the state, which is a Map private to this thread. This thread repeatedly checks for read and write requests, responding to them as they arrive.
We start 100 threads to issue reads to the state-owning thread via the reads queue. Each read requires constructing a ReadOp, sending it over the reads queue, and then receiving the result over the provided resp queue.
Similarly, we start 10 threads for writes, using a similar approach.
After letting the threads work for a second, we capture and report the operation counts.
Running this program shows that the thread-based state management example completes about 80,000 total operations:
For this particular case, the thread-based approach in Java is a bit more involved than a mutex-based one might be. It might be useful in certain cases though, for example where you have other queues involved or when managing multiple locks would be error-prone. You should use whichever approach feels most natural, especially with respect to understanding the correctness of your program.