Thread synchronization is a mechanism that controls access to shared resources when multiple threads are running concurrently. Its primary purpose is to ensure that only one thread can execute a critical section of code at a time, preventing data inconsistency and maintaining thread safety.
Why Is Synchronization Important?
1000
Deposit 500
Withdraw 200
This issue is known as a Race Condition.
How Synchronization Solves the Problem
1. One thread enters the critical section.
2. Other threads wait until the lock is released.
3. Shared data remains consistent.
Without Synchronization
Thread 1 → Read Balance = 1000
Thread 2 → Read Balance = 1000
Thread 1 → Update Balance = 1500
Thread 2 → Update Balance = 800
800
With Synchronization
Thread 1 → Complete Update
Thread 2 → Perform Update
1300
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Demo {
public static void main(String[] args)
throws InterruptedException {
Counter counter = new Counter();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(
counter.getCount());
}
}2000
Without synchronization, the result may be less than 2000 due to race conditions.
Ways to Achieve Synchronization in Java
1. Synchronized Method
public synchronized void update() {
// Critical section
}Locks the entire method.
2. Synchronized Block
public void update() {
synchronized (this) {
// Critical section
}
}Locks only the required code block.
3. ReentrantLock
Provides advanced locking features.
lock.lock();
try {
// Critical section
} finally {
lock.unlock();
}4. Concurrent Collections
Designed for thread-safe operations.
Real-World Example
Online Ticket Booking System
Multiple users try to book the last available seat.
Benefits of Synchronization
Potential Drawbacks
Therefore, synchronize only critical sections of code.
A concise interview answer is
Thread synchronization is the process of controlling access to shared resources in a multi-threaded environment. It ensures that only one thread can execute a critical section at a time, preventing race conditions and maintaining data consistency. In Java, synchronization can be achieved using synchronized methods, synchronized blocks, locks, and concurrent collections.
Last updated: 16 July 2026
Previous question: What are volatile variables in Java?
Next question: Can you describe a scenario where you would use wait() and notify() methods in thread communication?