This example demonstrates how to use stateful goroutines in Java using threads and concurrent data structures.
Running our program shows that the thread-based state management example completes about 80,000 total operations.
For this particular case, the thread-based approach was 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 channels involved or when managing multiple such locks would be error-prone. You should use whichever approach feels most natural, especially with respect to understanding the correctness of your program.
In Java, we’ve used Threads to represent the concept of goroutines, BlockingQueues for channels, and CompletableFutures for the response channels. The ConcurrentHashMap is used as a thread-safe alternative to the regular Map in the stateful thread.