🧠 What is Synchronization?
Synchronization is the process of controlling access to shared resources by multiple threads to prevent race conditions, data inconsistency, and memory visibility issues.
🔐 Why Is It Needed?
In multithreaded programs, multiple threads might:
- Read and write the same variables or objects
- Interleave their actions in unpredictable orders
Without synchronization:
- Data might be corrupted
- Threads may see stale (cached) values
- Behavior becomes nondeterministic and buggy
🔄 In Java: Synchronization = Locking a Monitor
In Java, synchronization is done using:
1. The synchronized keyword
- Can be used on methods or blocks
- Internally uses a monitor lock (a mutex) tied to an object
2. Explicit locks
- From
java.util.concurrent.locks(e.g.,ReentrantLock) - Give more control (try-lock, interruptibility, etc.)
🧪 Example
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
Here:
synchronizedensures only one thread at a time can runincrement()- Prevents two threads from doing
count++at the same time (which is not atomic!)
🔍 What Synchronization Ensures
| Feature | Explanation |
|---|---|
| ✅ Mutual Exclusion | Only one thread can execute critical code at a time |
| ✅ Visibility | Changes made by one thread are visible to others |
| ✅ Happens-Before | Synchronization establishes a happens-before relationship |
| ❌ Fairness (by default) | Threads are not guaranteed to get the lock in any specific order |
🔁 Other Forms of Synchronization
Besides synchronized, Java supports:
volatile— for visibility without lockingLock/ReentrantLock— for advanced lockingAtomicInteger, etc. — for lock-free synchronizationwait()/notify()— for thread coordination using monitor condition queues
🧠 Summary Definition
Synchronization in Java is the mechanism of coordinating multiple threads so that only one can access a critical section or shared resource at a time, and all changes are visible and consistent across threads.