Master Java Locks: From Pessimistic to Optimistic and Beyond
This article explains the full spectrum of Java concurrency locks—including pessimistic, optimistic, exclusive, shared, fair, unfair, segment, reentrant, and spin locks—detailing their principles, typical use cases, implementation details, and code examples to help you ace interview questions.
This article provides a comprehensive, diagram‑driven overview of the various locks used in Java concurrency, targeting interview preparation and deeper understanding of synchronization mechanisms.
Pessimistic Lock
A pessimistic lock assumes that concurrent operations on the same data will always conflict, so it acquires a lock for every access. The lock is implemented via mutual exclusion (e.g., synchronized or Lock), ensuring only one thread can modify the resource at a time.
Optimistic Lock
An optimistic lock assumes that conflicts are rare; it performs operations without locking and validates the data only at commit time. Typical implementations use the CAS (Compare‑And‑Swap) algorithm or versioning mechanisms provided by java.util.concurrent.atomic classes.
CAS works by comparing the current memory value with an expected value and, if they match, atomically updating it. It relies on low‑level primitives such as unsafe and the hardware instruction lock cmpxchg. Drawbacks include the ABA problem, wasted CPU cycles due to spinning, and the inability to guarantee atomicity of multi‑statement blocks.
Possible ABA (version) issue when a value changes from A to B and back to A.
High CPU consumption under heavy contention due to repeated retries.
Only single‑variable atomicity; larger critical sections still need synchronized or other mechanisms.
Exclusive and Shared Locks
An exclusive (or write) lock allows only one thread to hold it, granting both read and write access. In Java, synchronized and most Lock implementations are exclusive.
A shared (or read) lock permits multiple threads to hold it simultaneously, but only for read‑only operations. ReadWriteLock provides a shared read lock and an exclusive write lock.
Fair and Unfair Locks
A fair lock grants access to threads in the order they requested it, preventing starvation but incurring higher overhead. An unfair lock allows a thread to acquire the lock immediately if it becomes available, improving throughput at the risk of possible starvation.
In Java, synchronized is unfair, while ReentrantLock can be configured as fair (default is unfair).
// Create a non‑fair lock (true = fair, false = unfair)
Lock lock = new ReentrantLock(false); synchronizedis a keyword; Lock is an interface with implementations. synchronized cannot query lock state; Lock provides tryLock(). synchronized releases automatically; Lock requires explicit unlock(). synchronized is reentrant, non‑interruptible, and unfair; Lock defaults to unfair but can be set fair. synchronized uses Object.wait/notify; Lock can use Condition for scheduling. Lock can respond to interrupts during acquisition; synchronized cannot.
Segment Lock
Segment lock is a design pattern used in ConcurrentHashMap (JDK 1.7) to improve concurrency. The map is divided into multiple segments, each protected by its own lock, allowing multiple threads to operate on different buckets simultaneously.
static final class Segment<K,V> extends ReentrantLock implements Serializable {
transient volatile HashEntry<K,V>[] tables;
// ...
}
static final class HashEntry<K,V> {
final int hash;
final K key;
volatile V value;
volatile HashEntry<K,V> next;
}Reentrant Lock
A reentrant (or recursive) lock allows the same thread to acquire the lock multiple times without deadlocking. Both synchronized and ReentrantLock are reentrant in Java.
synchronized void getA() throws Exception {
Thread.sleep(1000);
getB();
}
synchronized void getB() throws Exception {
Thread.sleep(1000);
}Spin Lock
A spin lock makes a thread repeatedly attempt to acquire a lock in a loop (spinning) instead of blocking, reducing context‑switch overhead. However, if the lock is held for a long time, spinning wastes CPU cycles.
The article concludes with a reminder that mastering these lock concepts will greatly help in Java interview scenarios.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaEdge
First‑line development experience at multiple leading tech firms; now a software architect at a Shanghai state‑owned enterprise and founder of Programming Yanxuan. Nearly 300k followers online; expertise in distributed system design, AIGC application development, and quantitative finance investing.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
