Web Analytics

Synchronization

Advanced ~20 min read

Synchronization is the capability to control the access of multiple threads to any shared resource. It is used to prevent thread interference and consistency inconsistencies.

Race Conditions

A race condition occurs when two or more threads attempt to change shared data at the same time. This leads to unpredictable and incorrect results.

Example: Two threads trying to increment a counter count++ at the same time. The result might be 1 instead of 2!

The synchronized Keyword

You can use the synchronized keyword to ensure that only one thread can access a resource at a time.

1. Synchronized Method

public synchronized void increment() {
    count++;
}

2. Synchronized Block

More granular control. You lock only a specific part of the code.

public void increment() {
    synchronized(this) {
        count++;
    }
}

Full Example

This example demonstrates what happens without synchronization (commented out) and with synchronization.

Output
Click Run to execute your code

Summary

  • Race Conditions ruin data integrity.
  • Synchronized ensures only one thread executes a block/method at a time.
  • This comes at a performance cost, so use it only when sharing resources.