Synchronization
Synchronization is a mechanism that ensures only one thread can access a particular block of code or resource at a time, preventing multiple threads from causing conflicting changes to shared data simultaneously.
1. What is Synchronization?
Synchronization is a mechanism that ensures only one thread can access a particular block of code or resource at a time, preventing multiple threads from causing conflicting changes to shared data simultaneously.
2. Why is it used?
When multiple threads access and modify the same shared data (like a bank account balance) at the same time, it can lead to incorrect or corrupted results. Synchronization prevents this by allowing only one thread in at a time.
3. Real-Life Example
Think of a single-occupancy washroom with a lock. Only one person can go inside and lock the door at a time; others must wait outside until it's free. Synchronization enforces this same "one at a time" access to shared resources.
4. Syntax
javasynchronized void methodName() { // only one thread can execute this at a time }
5. Example Program
javaclass Counter { int count = 0; synchronized void increment() { count++; } } public class SynchronizationDemo { 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("Final count: " + counter.count); } }
Output:
Final count: 20006. Key Points to Remember
- The
synchronizedkeyword can be applied to methods or specific blocks of code. - Synchronization prevents data corruption but can slow down a program if overused, since threads must wait their turn.
- Without synchronization, shared data updated by multiple threads can produce unpredictable, incorrect results.