In the previous article, we explored the native keyword and learned how Java communicates with C/C++ libraries using JNI.
In this article, we’ll learn about one of the most important concepts in multithreaded programming:
synchronized
When multiple threads access the same object simultaneously, unexpected results can occur.
For example:
- Two users withdraw money from the same bank account at the same time.
- Multiple employees update the same inventory record.
- Several threads modify a shared counter.
Without proper synchronization, data can become inconsistent.
The synchronized keyword helps solve this problem by ensuring that only one thread can execute a critical section of code at a time.
By the end of this article, you’ll understand:
- What
synchronizedis - Why thread synchronization is needed
- Synchronized methods
- Synchronized blocks
- Object locks
- Illegal modifier combinations
- Advantages and disadvantages
- Common interview questions
What is the synchronized Keyword?
The synchronized keyword is used to control access to shared resources in a multithreaded environment.
If a method or block is declared as synchronized, only one thread at a time can execute that code for a given object.
It is applicable to:
- Methods
- Blocks
It is not applicable to:
- Classes
- Variables
- Constructors
Why Do We Need Synchronization?
Imagine a bank account with a balance of ₹10,000.
Two threads attempt to withdraw ₹7,000 simultaneously.
Without synchronization:
Balance = ₹10,000
│
├───────────────┐
▼ ▼
Thread A Thread B
Withdraw ₹7,000 Withdraw ₹7,000
│ │
▼ ▼
Both read ₹10,000 before either updates it
│
▼
Final Balance = Incorrect
Enter fullscreen mode Exit fullscreen mode
Both threads may think enough money exists and complete the withdrawal, leading to inconsistent data.
How synchronized Solves the Problem
With synchronization:
Thread A
│
Gets Object Lock
│
Executes Method
│
Releases Lock
│
───────────────►
Thread B Gets Lock
Enter fullscreen mode Exit fullscreen mode
Only one thread can execute the synchronized code at a time.
Syntax
Synchronized Method
public synchronized void withdraw(double amount) {
}
Enter fullscreen mode Exit fullscreen mode
Synchronized Block
synchronized (this) {
// Critical section
}
Enter fullscreen mode Exit fullscreen mode
How a Synchronized Method Works
Consider this example:
class BankAccount {
private double balance = 10000;
public synchronized void withdraw(double amount) {
balance -= amount;
System.out.println("Remaining Balance: " + balance);
}
}
Enter fullscreen mode Exit fullscreen mode
Step-by-Step Explanation
Step 1
A thread calls the withdraw() method.
Step 2
The JVM checks whether another thread already owns the object’s lock.
Step 3
If the lock is available, the thread acquires it.
Step 4
The method executes.
Step 5
The lock is released after the method completes.
What Is an Object Lock?
Every Java object has an associated monitor (lock).
When a synchronized instance method is called:
- The thread acquires the object’s lock.
- Other threads attempting to execute synchronized methods on the same object must wait.
BankAccount Object
│
▼
Object Lock
│
▼
Thread 1 ✅ Running
Thread 2 ⏳ Waiting
Thread 3 ⏳ Waiting
Enter fullscreen mode Exit fullscreen mode
Synchronized Methods
Example:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
System.out.println(count);
}
}
Enter fullscreen mode Exit fullscreen mode
Only one thread can execute increment() on the same Counter object at a time.
Synchronized Blocks
Sometimes only a small portion of a method needs synchronization.
Instead of synchronizing the entire method, synchronize only the critical section.
Example:
class Inventory {
private int stock = 100;
public void purchase(int quantity) {
System.out.println("Validating request...");
synchronized (this) {
stock -= quantity;
}
System.out.println("Purchase completed.");
}
}
Enter fullscreen mode Exit fullscreen mode
Why Use a Synchronized Block?
Only the code that modifies shared data is synchronized.
This reduces waiting time and improves performance.
Method vs Block Synchronization
Synchronized Method Synchronized Block Entire method is locked Only selected code is locked Easier to write More flexible Can reduce performance Better performance for large methods
Illegal Combination: abstract synchronized
An abstract method has no implementation.
Example:
abstract void process();
Enter fullscreen mode Exit fullscreen mode
A synchronized method requires executable code because it acquires and releases locks.
These two concepts conflict.
Incorrect:
public abstract synchronized void process();
Enter fullscreen mode Exit fullscreen mode
Compile-Time Error
illegal combination of modifiers:
abstract and synchronized
Enter fullscreen mode Exit fullscreen mode
Why?
An abstract method has no body.
Without a body, there is nothing to synchronize.
Advantages of synchronized
1. Prevents Data Inconsistency
Only one thread modifies shared data at a time.
2. Simplifies Thread Safety
The JVM manages locking automatically.
3. Easy to Understand
Using the synchronized keyword is straightforward compared to manual lock management.
Disadvantages of synchronized
1. Reduced Performance
Threads waiting for a lock cannot continue execution.
2. Increased Waiting Time
High contention can cause many threads to remain blocked.
3. Scalability Issues
Excessive synchronization may reduce throughput in highly concurrent applications.
Common Beginner Mistakes
Mistake 1: Synchronizing Everything
Incorrect approach:
public synchronized void processLargeFile() {
// Hundreds of lines of code
}
Enter fullscreen mode Exit fullscreen mode
Prefer synchronizing only the critical section whenever possible.
Mistake 2: Assuming Synchronized Makes Code Faster
Synchronization improves correctness, not speed.
Mistake 3: Thinking Every Object Shares One Lock
Each Java object has its own monitor.
Different objects can execute synchronized methods simultaneously.
Mistake 4: Forgetting That Static Methods Use a Different Lock
A synchronized instance method locks the current object (this).
A synchronized static method locks the Class object.
This distinction is a common interview topic.
Best Practices
- Synchronize only code that accesses shared mutable data.
- Prefer synchronized blocks over synchronized methods when only a small section needs protection.
- Keep synchronized sections short.
- Avoid unnecessary synchronization in single-threaded applications.
- Consider higher-level concurrency utilities (
java.util.concurrent) for complex concurrent programming.
Interview Questions
1. What is the purpose of the synchronized keyword?
It ensures that only one thread at a time executes a synchronized method or block for a given lock.
Why interviewers ask
To evaluate your understanding of thread safety.
2. Where can synchronized be applied?
- Methods
- Blocks
3. Can constructors be synchronized?
No.
Constructors cannot be declared synchronized.
4. What is synchronized on an instance method?
The current object (this) is locked.
5. What is synchronized on a static method?
The Class object is locked.
6. Why is abstract synchronized illegal?
Because an abstract method has no implementation, while synchronization requires executable code.
7. Which is better: synchronized method or synchronized block?
Generally, synchronized blocks provide better flexibility and can improve performance by locking only the required code.
Quick Memory Trick 🧠
Remember LOCK:
L → Lock Object
O → One Thread
C → Critical Section
K → Keep Data Consistent
Enter fullscreen mode Exit fullscreen mode
Whenever you see synchronized, think LOCK.
Key Takeaways
-
synchronizedis applicable only to methods and blocks. - It prevents multiple threads from executing critical sections simultaneously.
- Every Java object has its own monitor (lock).
- Synchronized methods lock the entire method.
- Synchronized blocks lock only selected code.
-
abstract synchronizedis an illegal modifier combination. - Synchronization improves thread safety but may reduce performance.
- Use synchronization only when shared mutable data is involved.
If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.
Happy Coding!
답글 남기기