Thread Synchronization in Java
1. Introduction
Thread synchronization in Java means controlling the access of multiple threads to shared resources. It is
used to avoid problems such as race conditions, data inconsistency, and to ensure thread safety.
2. Why is Synchronization Needed?
Why is Synchronization Needed?
- To prevent two threads from accessing shared data at the same time.
- To avoid incorrect output or data loss.
- To make the program thread-safe.
- To maintain correct results in multi-threading.
3. Types of Synchronization in Java
Types of Synchronization in Java:
1. Synchronized Method:
Lock is applied to the entire method.
public synchronized void increment() {
count++;
2. Synchronized Block:
Only a specific part of code is locked.
synchronized(this) {
count++;
3. Static Synchronization:
Used for static methods (class-level lock).
Thread Synchronization in Java
public static synchronized void show() {
// code
4. Example Code
class Counter {
int count = 0;
public synchronized void increment() {
count++;
}
}
public class Example {
public static void main(String[] args) throws Exception {
Counter c = new Counter();
Thread t1 = new Thread(() -> {
for(int i = 0; i < 1000; i++) c.increment();
});
Thread t2 = new Thread(() -> {
for(int i = 0; i < 1000; i++) c.increment();
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final Count: " + c.count);
}
}
5. Conclusion
Without Synchronization:
Output may be less than 2000 due to race condition.
With Synchronization:
Thread Synchronization in Java
Output will be correct (Final Count: 2000).
Conclusion:
- Synchronization is used to control thread access to shared data.
- It ensures data consistency and thread safety.
- Java provides 'synchronized' keyword for this purpose.