What is Synchronization in Java?
Synchronization is used to prevent thread interference and data inconsistency in multithreaded environments.
When multiple threads access shared resources (like a variable, method, or file), synchronization ensures that only one thread can access the resource at a time.
Why is it Needed?
Without synchronization, multiple threads can modify shared data simultaneously, causing inconsistent or incorrect results.
How to Use Synchronization
Java provides several ways to implement synchronization:
synchronized
methodssynchronized
blocks- Static synchronization
- Locks (from
java.util.concurrent.locks
) – for advanced use
Example Without Synchronization (Problem Case)
class Counter {
int count = 0;
void increment() {
count++;
}
}
public class WithoutSync {
public static void main(String[] args) throws InterruptedException {
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 (without sync): " + c.count);
}
}
Output (may vary):
Final Count (without sync): 1905
Expected: 2000 Reason: Race condition due to lack of synchronization.
Example With Synchronization
class Counter {
int count = 0;
synchronized void increment() {
count++;
}
}
public class WithSync {
public static void main(String[] args) throws InterruptedException {
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 (with sync): " + c.count);
}
}
Output:
Final Count (with sync): 2000
Synchronized Block (More Control)
class Printer {
void printMessage(String msg) {
synchronized(this) {
for (int i = 1; i <= 3; i++) {
System.out.println(msg + " - " + i);
try { Thread.sleep(100); } catch (Exception e) {}
}
}
}
}
public class SyncBlockExample {
public static void main(String[] args) {
Printer printer = new Printer();
Thread t1 = new Thread(() -> printer.printMessage("Hello"));
Thread t2 = new Thread(() -> printer.printMessage("World"));
t1.start();
t2.start();
}
}
synchronized(this)
locks only part of the code, not the whole method — more efficient.
Static Synchronization
- If a method is static, use
synchronized
to prevent simultaneous access by multiple threads to class-level data.
class StaticExample {
static int count = 0;
synchronized static void increment() {
count++;
}
}
Summary of synchronized
Type | Locks On | Used For |
---|---|---|
synchronized method |
Entire method | Simpler, but may lock too much code |
synchronized(this) block |
Specific block | More efficient, locks only what’s needed |
static synchronized |
Class object | Synchronizes static methods |
Best Practices
- Use minimal synchronized blocks to improve performance.
- Avoid deadlocks by not holding multiple locks at once.
- Use
ReentrantLock
for advanced locking needs.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.