What is Synchronization in Java: Explanation and Example
synchronization is a mechanism that controls access to shared resources by multiple threads to prevent conflicts and data inconsistency. It ensures that only one thread can execute a block of code or method at a time when accessing shared data.How It Works
Imagine you and your friend want to use the same notebook to write notes. If both write at the same time, the notes get mixed up and confusing. Synchronization in Java works like a lock on that notebook, allowing only one person to write at a time.
In Java, when multiple threads try to access the same resource (like a variable or method), synchronization makes sure only one thread can enter the critical section of code at once. Other threads wait their turn, preventing errors caused by simultaneous changes.
Example
This example shows two threads trying to add money to the same bank account. Without synchronization, the final balance might be wrong. Using synchronized ensures the balance updates correctly.
class BankAccount { private int balance = 0; public synchronized void deposit(int amount) { int newBalance = balance + amount; // Simulate delay try { Thread.sleep(10); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } balance = newBalance; } public int getBalance() { return balance; } } public class SyncExample { public static void main(String[] args) throws InterruptedException { BankAccount account = new BankAccount(); Thread t1 = new Thread(() -> { for (int i = 0; i < 100; i++) { account.deposit(1); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 100; i++) { account.deposit(1); } }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Final balance: " + account.getBalance()); } }
When to Use
Use synchronization when multiple threads share and modify the same data or resource. It prevents problems like data corruption or unexpected results.
Common real-world cases include updating bank accounts, managing inventory in online stores, or handling shared counters in applications. Without synchronization, these operations can produce wrong results or crash the program.
Key Points
- Synchronized keyword locks methods or blocks to allow one thread at a time.
- It prevents race conditions where threads interfere with each other.
- Overusing synchronization can slow down programs, so use it only when needed.
- Java provides other concurrency tools, but synchronization is the basic way to control thread access.