Thread Synchronization
When multiple threads access the same resource at the same time, data can become inconsistent or corrupted.
Thread Synchronization in Java ensures that only one thread accesses a shared resource at a time, maintaining data integrity.
Why Synchronization Is Needed
Multithreading improves performance, but it also introduces risks when threads share data.
Without synchronization, problems like incorrect values, unexpected behavior, and system crashes can occur.
Real Problem Without Synchronization
Consider a bank account where multiple threads withdraw money.
class Account {
int balance = 1000;
void withdraw(int amount) {
balance -= amount;
System.out.println("Balance: " + balance);
}
}
If two threads withdraw money at the same time, the balance can become incorrect.
Using synchronized Method
The simplest way to protect shared data is by using the
synchronized keyword.
class Account {
int balance = 1000;
synchronized void withdraw(int amount) {
balance -= amount;
System.out.println("Balance: " + balance);
}
}
Now only one thread can execute the method at a time.
Synchronization Using synchronized Block
Sometimes you only need to synchronize a specific section of code, not the entire method.
void withdraw(int amount) {
synchronized (this) {
balance -= amount;
System.out.println("Balance: " + balance);
}
}
This improves performance by locking only the critical section.
Example with Multiple Threads
Let us simulate two users withdrawing money at the same time.
class User extends Thread {
Account account;
User(Account account) {
this.account = account;
}
public void run() {
account.withdraw(500);
}
public static void main(String[] args) {
Account acc = new Account();
User u1 = new User(acc);
User u2 = new User(acc);
u1.start();
u2.start();
}
}
Synchronization ensures correct balance updates.
What Is a Monitor Lock?
When a thread enters a synchronized block or method, it acquires a monitor lock.
Other threads must wait until the lock is released.
Common Synchronization Issues
- Deadlock – threads waiting on each other
- Reduced performance due to excessive locking
- Complex debugging
Best Practices
- Synchronize only critical code
- Avoid nested locks
- Keep synchronized blocks small
- Test multithreaded code thoroughly
Industry Example
Synchronization is heavily used in:
- Banking systems
- Ticket booking platforms
- Inventory management systems
- Concurrent web servers
Key Takeaways
- Synchronization prevents data inconsistency
- synchronized keyword controls thread access
- Essential for safe multithreaded applications
In the next lesson, we will explore File Handling and learn how Java works with files and streams.