What is thread synchronization?
Thread synchronization is the simultaneous execution of two or more threads sharing critical resources. Threads should be synchronized to avoid critical resource usage conflicts. Otherwise, conflicts can arise when parallel threads try to change a common variable at the same time.
Consider the following example to illustrate thread synchronization: Three threads - A, B, and C - are running at the same time and need to access a critical Z resource. To avoid conflicts when accessing Z, threads A, B and C must be synchronized. So if A accesses Z and B tries to access Z too, security measures must be taken to avoid B's access to Z until A finishes its operation and Z leaves.
Two synchronization strategies are used in Java to avoid thread interference and memory consistency errors:
Synchronized Method: Contains the synchronized keyword in its declaration. When a thread calls a synchronized method, the synchronized method automatically captures the intrinsic lock on the object of that method and releases it when the method returns, even if that return was caused by an uncaught exception.
Synchronized instruction: Declares a block of code to be synchronized. Unlike synchronized methods, synchronized statements should identify the objects that will provide the intrinsic lock. These instructions are useful to improve simultaneity with fine-grained synchronization, as they will allow you to avoid unnecessary deadlocks.