Introduction
As we saw in Chapter 1, Threading Basics, it is problematic to use a shared object simultaneously from several threads. It is very important to synchronize those threads so that they perform operations on that shared object in a proper sequence. In a multithreaded counter recipe, we met a problem called the race condition. It happened because the execution of those multiple threads were not synchronized properly. When one thread performs the increment and decrement operations, the other threads must wait for their turn. This general problem is often referred to as thread synchronization.
There are several ways to achieve thread synchronization. First, if there is no shared object, there is no need for synchronization at all. Surprisingly, it is very often that we can get rid of complex synchronization constructs by just redesigning your program and removing a shared state. If it's possible, just avoid using a single object from several threads.
If we must have a shared...