Java concurrency is one of the most important topics for building scalable, reliable, and high-performance backend applications.
In modern enterprise applications, multiple threads frequently access shared resources such as:
- Bank account balances
- Payment transaction records
- Order processing states
- Inventory quantities
- Shared in-memory caches
- Transaction counters
When multiple threads modify shared data simultaneously, race conditions, data inconsistency, and unexpected application behavior can occur.
Java provides several synchronization mechanisms to handle these problems.
Three commonly used approaches are:
synchronized-
LockAPI - Atomic classes (
AtomicInteger,AtomicLong,AtomicReference, etc.)
But which one should we use?
Let's understand their internal behavior, differences, practical implementations, and real-world use cases.
1. Understanding the Race Condition
Consider a simple bank account application.
public class BankAccount {
private int balance = 1000;
public void withdraw(int amount) {
balance = balance - amount;
}
public int getBalance() {
return balance;
}
}
Suppose two threads execute the withdrawal operation simultaneously:
- Thread 1 withdraws ₹500.
- Thread 2 withdraws ₹300.
Both threads read the original balance before either completes its update.
This can produce an incorrect final balance.
The problem is that the operation:
balance = balance - amount;
is not atomic.
It involves multiple steps:
- Read the current balance.
- Calculate the new balance.
- Write the updated balance.
Without synchronization, concurrent execution can cause a lost update.
Solution: Protect shared mutable state using an appropriate concurrency mechanism.
2. synchronized – Intrinsic Locking
Java's synchronized keyword provides built-in mutual exclusion.
Only one thread can execute a synchronized block protected by the same monitor at a time.
Example: Method-Level Synchronization
public class BankAccount {
private int balance = 1000;
public synchronized void withdraw(int amount) {
if (balance >= amount) {
balance -= amount;
}
}
public synchronized int getBalance() {
return balance;
}
}
When a thread enters a synchronized instance method, it acquires the object's intrinsic monitor lock.
Other threads attempting to enter synchronized methods or blocks protected by that same monitor must wait.
Block-Level Synchronization
Instead of synchronizing an entire method, we can synchronize only the critical section.
public void withdraw(int amount) {
synchronized (this) {
if (balance >= amount) {
balance -= amount;
}
}
}
This can reduce unnecessary lock contention when other parts of the method do not need protection.
Static Synchronization
public static synchronized void process() {
// Thread-safe static operation
}
A static synchronized method acquires the monitor associated with the class's Class object rather than an individual instance.
How synchronized Works Internally
At the JVM level, synchronized operations use monitor-related mechanisms.
The JVM manages monitor acquisition and release. When a thread exits a synchronized block, normally or exceptionally, the monitor is released automatically.
Modern JVM implementations also optimize synchronization using techniques such as lock elimination and lock coarsening where applicable.
Important: Synchronization also establishes a happens-before relationship. Changes made by one thread before releasing a monitor become visible to another thread after it subsequently acquires the same monitor.
When to Use synchronized?
- Simple critical sections.
- Protecting shared mutable objects.
- Maintaining consistency across multiple related fields.
- When explicit lock management is unnecessary.
3. Lock API – Explicit Locking
Java provides the java.util.concurrent.locks package for more flexible synchronization.
The most commonly used implementation is ReentrantLock.
Unlike synchronized, the Lock API provides additional capabilities:
- Explicit lock acquisition and release.
- Non-blocking lock acquisition using
tryLock(). - Interruptible lock acquisition.
- Optional fairness policy.
- Multiple condition variables using
Condition.
Example: ReentrantLock
import java.util.concurrent.locks.ReentrantLock;
public class BankAccount {
private int balance = 1000;
private final ReentrantLock lock =
new ReentrantLock();
public void withdraw(int amount) {
lock.lock();
try {
if (balance >= amount) {
balance -= amount;
}
} finally {
lock.unlock();
}
}
public int getBalance() {
lock.lock();
try {
return balance;
} finally {
lock.unlock();
}
}
}
Why finally Is Important
Consider this scenario:
A thread acquires a lock and an exception occurs during business processing.
If the lock is not released, other threads may remain blocked indefinitely.
That's why we should always release explicitly acquired locks inside a finally block.
tryLock() – Avoid Waiting Indefinitely
One important advantage of ReentrantLock is tryLock().
It allows a thread to attempt acquiring a lock without waiting indefinitely.
public void processPayment() {
if (lock.tryLock()) {
try {
System.out.println(
"Processing payment..."
);
} finally {
lock.unlock();
}
} else {
System.out.println(
"Resource is currently busy"
);
}
}
We can also use a timed lock attempt:
if (lock.tryLock(2, TimeUnit.SECONDS)) {
try {
// Business logic
} finally {
lock.unlock();
}
}
This can be useful when an application needs to avoid waiting indefinitely for a contended resource.
Fairness in ReentrantLock
private final ReentrantLock lock =
new ReentrantLock(true);
The true parameter enables a fairness policy.
A fair lock generally favors the longest-waiting thread when granting access.
However, fairness can reduce throughput and does not guarantee fair scheduling of application threads.
Condition – Advanced Thread Coordination
The Lock API also supports Condition objects.
private final ReentrantLock lock =
new ReentrantLock();
private final Condition condition =
lock.newCondition();
Threads can wait for a condition using:
condition.await();
Another thread can signal waiting threads using:
condition.signal();
This is useful in producer-consumer implementations and other coordination scenarios.
As with Object.wait(), condition waits should generally be used inside a loop that checks the required condition.
4. Atomic Classes – Lock-Free Operations
Java provides atomic classes in the java.util.concurrent.atomic package.
Examples include:
- AtomicInteger
- AtomicLong
- AtomicBoolean
- AtomicReference
- LongAdder
- LongAccumulator
These classes support thread-safe operations using atomic updates.
Many atomic operations use Compare-And-Set (CAS) mechanisms.
What Is CAS?
CAS stands for Compare-And-Set.
It works conceptually as follows:
- Read the current value.
- Compare it with the expected value.
- If both match, update it with the new value.
- If another thread changed the value, retry or report failure.
The operation succeeds only if the expected value is still current.
Example: AtomicInteger
import java.util.concurrent.atomic.AtomicInteger;
public class TransactionCounter {
private final AtomicInteger counter =
new AtomicInteger(0);
public void increment() {
counter.incrementAndGet();
}
public int getCount() {
return counter.get();
}
}
Multiple threads can safely increment the counter without explicitly using synchronized or ReentrantLock.
CAS Example
AtomicInteger balance =
new AtomicInteger(1000);
int current = balance.get();
boolean updated =
balance.compareAndSet(
current,
current - 100
);
If another thread changes the balance between reading and updating, the CAS operation fails.
The application can retry with the latest value if appropriate.
AtomicReference
AtomicReference is useful when we need atomic updates of object references.
import java.util.concurrent.atomic.AtomicReference;
public class PaymentStatus {
private final AtomicReference<String> status =
new AtomicReference<>("PENDING");
public boolean completePayment() {
return status.compareAndSet(
"PENDING",
"COMPLETED"
);
}
}
This ensures that only one thread can successfully transition the status from PENDING to COMPLETED using this operation.
What About LongAdder?
For highly concurrent counters, LongAdder can provide better throughput than AtomicLong because it distributes updates across multiple internal cells.
import java.util.concurrent.atomic.LongAdder;
public class RequestMetrics {
private final LongAdder requestCount =
new LongAdder();
public void recordRequest() {
requestCount.increment();
}
public long getRequestCount() {
return requestCount.sum();
}
}
LongAdder is particularly useful for metrics and statistics where highly contended increments are common.
However, its sum() method is not an atomic snapshot during concurrent updates.
It should not be used where every read must represent a strictly consistent transactional value.
5. synchronized vs Lock vs Atomic – Key Differences
| Feature | synchronized | ReentrantLock | Atomic Classes |
|---|---|---|---|
| Lock mechanism | Intrinsic monitor | Explicit lock | CAS / atomic operations |
| Lock release | Automatic | Manual | Not applicable for ordinary atomic operations |
| tryLock() | No | Yes | CAS operations can fail immediately |
| Interruptible acquisition | No direct equivalent | Yes | Depends on operation |
| Fairness option | No | Yes | No |
| Multiple conditions | wait/notify | Condition | Not built in |
| Multiple-field protection | Yes | Yes | Requires additional coordination |
| Best suited for | Critical sections | Complex locking | Independent atomic state updates |
6. Real-World Banking Application Use Cases
Let's understand where these mechanisms fit in an enterprise banking application.
Scenario 1: Updating Customer Account Details
A customer account contains multiple related fields:
- Account balance
- Account status
- Transaction limits
When multiple fields must be updated consistently under one shared in-memory synchronization boundary, synchronized or Lock can be appropriate.
Scenario 2: Transaction Request Counter
A payment service tracks the number of incoming requests.
Using AtomicLong or LongAdder is a good approach depending on whether exact atomic reads or high-throughput metrics are required.
Scenario 3: Payment Status Transition
A payment moves through different states:
PENDING → PROCESSING → COMPLETED
AtomicReference with compareAndSet() can prevent multiple threads from successfully applying the same state transition.
Scenario 4: Resource Coordination
A service manages a shared in-memory resource that requires timed lock acquisition and interruption support.
ReentrantLock provides more flexibility than synchronized.
Important architectural consideration:
Java synchronization only coordinates threads sharing the same JVM-level synchronization object.
In distributed microservices, multiple application instances may process the same payment simultaneously.
For distributed consistency, we need additional mechanisms such as:
- Database transactions.
- Optimistic locking with version columns.
- Pessimistic database locking.
- Unique constraints and idempotency keys.
- Distributed coordination where justified.
Never assume that synchronized or AtomicInteger can guarantee consistency across multiple service instances.
7. Performance Considerations
There is no universal winner among synchronized, Lock, and Atomic classes.
Performance depends on:
- Number of concurrent threads.
- Lock contention.
- Duration of critical sections.
- Frequency of updates.
- CPU architecture.
- JVM optimizations.
- Application workload.
A few practical guidelines:
- Prefer synchronized for straightforward mutual exclusion.
- Use ReentrantLock when you need timed acquisition, interruptibility, fairness, or multiple conditions.
- Use atomic classes for independent state updates.
- Consider LongAdder for highly contended metrics counters.
- Avoid unnecessarily large synchronized blocks.
- Never hold locks while performing slow network or database operations unless absolutely necessary.
For performance-sensitive systems, validate assumptions using JMH rather than relying on theoretical comparisons.
8. Interview Questions – Frequently Asked
Q1. What is the main difference between synchronized and ReentrantLock?
synchronized provides intrinsic locking with automatic release. ReentrantLock provides explicit locking with advanced features such as tryLock(), interruptible acquisition, and configurable fairness.
Q2. Is synchronized reentrant?
Yes. The same thread can acquire the same intrinsic monitor multiple times.
Q3. What is CAS?
Compare-And-Set is an atomic operation that updates a value only if it matches an expected value.
Q4. Are AtomicInteger operations thread-safe?
Yes. Its atomic methods provide thread-safe updates to the integer value.
Q5. Can AtomicInteger replace synchronized completely?
No. AtomicInteger is suitable for individual atomic state operations. It does not automatically protect complex operations involving multiple fields or multiple independent objects.
Q6. What happens if unlock() is not called?
The lock remains held, potentially preventing other threads from acquiring it. Always use try-finally.
Q7. What is the difference between AtomicLong and LongAdder?
AtomicLong provides atomic updates and reads of one value. LongAdder distributes updates across cells to reduce contention, making it useful for high-throughput statistics.
Q8. Does synchronized guarantee thread execution order?
No. It guarantees mutual exclusion and memory visibility through monitor synchronization, but does not guarantee the order in which threads acquire the monitor.
Conclusion
Choosing the right synchronization mechanism is essential for building reliable concurrent Java applications.
Remember these practical guidelines:
- synchronized: Simple and effective mutual exclusion.
- ReentrantLock: Advanced locking and thread coordination.
- Atomic Classes: Efficient atomic updates for independent shared state.
- LongAdder: High-throughput counters and metrics.
As Java developers working on enterprise applications, understanding these mechanisms is more important than simply knowing their syntax.
The real skill is identifying the concurrency problem and selecting the simplest mechanism that guarantees correctness without introducing unnecessary complexity.
Write thread-safe code. Design for concurrency. Build reliable systems.
About the Author
Ramu Boya | Ram The Architect (RTA)
Java Backend | Spring Boot | Microservices | System Design | Cloud Architecture | GenAI
Sharing practical insights on enterprise Java engineering, distributed systems, fintech architecture, and modern application development.

Top comments (0)