Synchronization
Synchronization is another critical Java concept that we should grasp as we seek to fully understand concurrency. As we indicated earlier, we employ synchronization to avoid race conditions.
Race conditions
The condition when multiple threads attempt to modify a shared resource at the same time. The results of this situation are unpredictable and should be avoided.
Let’s look at how we can implement synchronization in our Java applications by looking at several code snippets. First, we demonstrated adding the synchronized
keyword to a method’s declaration. This is how we can ensure that only one thread at a time can execute the method on a specific object:
public class Counter { private int count = 0; public synchronized void increment() { count++; } public synchronized int getCount() {...