Different synchronization approaches
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
.
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 access takes a long time, it creates a bottleneck that might eliminate the advantage of having many threads working in parallel. Or, if one thread blocks access to one resource while waiting for access to another resource and the second thread blocks access to the second resource...