In this recipe, you will learn about the two most popular methods of managing concurrent access to common resources in Java: synchronized method and synchronized block.
Different synchronization approaches
Getting ready
Two or more threads modifying the same value while other threads read it is the most general description of one of the problems of concurrent access. Subtler problems include thread interference and memory consistency errors, which both produce unexpected results in seemingly benign fragments of code. We are going to demonstrate such cases and ways to avoid them.
At first glance, it seems quite straightforward: just allow only one thread at a time to modify/access the resource and that's it. But if the...