Synchronization in Java is a mechanism used to control **multiple threads** accessing shared
resources at the same time. It helps prevent **data inconsistency** and **race conditions**.
## Why Synchronization is Needed: When two or more threads modify the same data simultaneously, unexpected results can occur.
Example without synchronization:
```java
class Counter {int count = 0;
void increment() {count++;}
}
```
If multiple threads call `increment()` together, the final value may be incorrect because `count++` is not an atomic operation.
---
class MyThread1 extends Thread {
Table t;
MyThread1(Table t) { this.t = t; }
public void run() {t.printTable(5);}
}
class MyThread2 extends Thread {
Table t;
MyThread2(Table t) {this.t = t;}
public void run() {t.printTable(100);}
}
public class Main {public static void main(String[] args) {
Table obj = new Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();}
}
```
Because the method is synchronized, one thread finishes first before the other enters the method.
--- # Advantages of Synchronization: Prevents race condition, Maintains data consistency, Ensures thread safety
---
Disadvantages: Slower performance due to locking, Possibility of deadlock if not used carefully.
---
Important Terms
Race Condition
Occurs when multiple threads access shared data simultaneously and result depends on execution order.
Deadlock: Two threads wait forever for each other’s lock.
Thread Safety: Code behaves correctly when accessed by multiple threads.
---
Modern Alternatives: Java also provides advanced concurrency utilities in:
* java.util.concurrent
Examples:
* `ReentrantLock`, `AtomicInteger`, `ExecutorService`, `ConcurrentHashMap`
These often provide better scalability than traditional synchronization.