Synchronized Blocks & Methods
About
Why is Synchronization Needed?
Example Without Synchronization (Race Condition)
class SharedResource {
private int count = 0;
void increment() { // Not synchronized
count++;
}
int getCount() {
return count;
}
}
public class RaceConditionExample {
public static void main(String[] args) throws InterruptedException {
SharedResource resource = new SharedResource();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
resource.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
resource.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final Count: " + resource.getCount()); // Expected: 2000, but may be incorrect due to race condition
}
}Output (Inconsistent Results)
Synchronized Methods
Syntax
Example of Synchronized Method
Output (Always Correct)
How It Works?
When to Use?
Synchronized Blocks
Syntax
Example 1
Example 2
How It Works?
When to Use?
Class-Level Synchronization (Static Methods)
Example
When to Use?
Class-Level Lock vs. Instance-Level Lock
Comparison Table
Last updated