What Does Thread Synchronization Mean?
Thread synchronization is the concurrent execution of two or more threads that share critical resources. Threads should be synchronized to avoid critical resource use conflicts. Otherwise, conflicts may arise when parallel-running threads attempt to modify a common variable at the same time.
Techopedia Explains Thread Synchronization
To clarify thread synchronization, consider the following example: three threads – A, B, and C – are executed concurrently and need to access a critical resource, Z. To avoid conflicts when accessing Z, threads A, B, and C must be synchronized. Thus, when A accesses Z, and B also tries to access Z, B’s access of Z must be avoided with security measures until A finishes its operation and comes out of Z.
In Java, two synchronization strategies are used to prevent thread interference and memory consistency errors:
- Synchronized Method: Includes the synchronized keyword in its declaration. When a thread invokes a synchronized method, synchronized method automatically acquires the intrinsic lock for that method’s object and releases it when the method returns, even if that return was caused by an uncaught exception.
- Synchronized Statement: Declares a block of code to be synchronized. Unlike synchronized methods, synchronized statements should specify the objects that provide the intrinsic lock. These statements are useful for improving concurrency with fine-grained synchronization, as they enable the avoidance of unnecessary blocking.