Mastering Java Locks: From Optimistic to Biased – A Complete Guide

This article offers a comprehensive overview of Java's lock mechanisms, detailing each lock type, its underlying principle, typical use cases, differences between synchronized and Lock, and practical code examples for implementing read‑write locks and optimizing concurrency.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Mastering Java Locks: From Optimistic to Biased – A Complete Guide

This article provides a comprehensive overview of Java lock mechanisms, covering their principles, typical applications, and implementation details.

1. Optimistic Lock

Optimistic Lock assumes a read‑heavy, write‑light environment; reads proceed without locking, while writes compare the current value with an expected value and only update if they match, using CAS for atomicity.

In Java, optimistic locking is implemented via CAS (Compare‑And‑Swap), which repeatedly compares the current value with the expected value and updates it atomically.

2. Pessimistic Lock

Pessimistic Lock assumes a write‑heavy scenario; every read or write operation acquires a lock, blocking other threads until the lock is released.

Java provides pessimistic locking through synchronized methods/blocks and ReentrantLock.

3. Spin Lock

Spin Lock makes a thread repeatedly execute a busy‑wait loop (spin) instead of being suspended.

Advantages: avoids the overhead of thread context switches. Disadvantages: consumes CPU cycles while spinning; if the spin duration is long, it wastes processor resources.

Default spin count is 10 and can be changed with the JVM option -XX:PreBlockSpin. Adaptive spinning adjusts the spin time based on previous attempts and the lock owner’s state.

In Java, spin locks are realized by repeatedly performing CAS until it succeeds.

4. Reentrant (Recursive) Lock

Reentrant Lock allows the same thread to acquire the same lock multiple times without blocking.

Implementation uses a custom synchronizer that increments a hold count on each acquisition and decrements it on release.

Java provides ReentrantLock and the synchronized keyword for reentrant locking.

Interview question: If a reentrant lock is acquired twice but released only once, the thread will deadlock because the lock count remains non‑zero.

5. Read‑Write Lock

Read‑Write Lock uses ReentrantReadWriteLock to allow multiple concurrent readers while writes acquire an exclusive lock.

Read lock: multiple threads can hold it simultaneously.

Write lock: only one thread can hold it at a time.

Usage example:

private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
// acquire read lock
rwLock.readLock().lock();
// release read lock
rwLock.readLock().unlock();
// acquire write lock
rwLock.writeLock().lock();
// release write lock
rwLock.writeLock().unlock();

In Java, the read‑write lock is represented by ReentrantReadWriteLock.

6. Fair Lock

Fair Lock grants lock acquisition in the order of request (FIFO), preventing thread starvation.

7. Unfair Lock

Unfair Lock allows threads to acquire the lock out of order, often yielding higher throughput but risking starvation.

In Java, synchronized is an unfair lock; ReentrantLock can be configured as fair or unfair (default unfair).

8. Shared Lock

Shared Lock permits multiple threads to hold the lock simultaneously for reading, similar to optimistic or read‑write locks.

Java uses ReentrantReadWriteLock for shared locking.

9. Exclusive Lock

Exclusive Lock allows only one thread to hold the lock at any time.

Java implementations include synchronized and ReentrantLock.

10. Heavyweight Lock

Heavyweight lock is realized by synchronized using the OS monitor (a native mutex), which incurs high context‑switch costs.

To reduce this overhead, the JVM introduces lightweight and biased locks.

11. Lightweight Lock

Lightweight Lock uses CAS to avoid OS mutexes when there is no contention, providing faster synchronization.

If contention appears, it inflates to a heavyweight lock.

12. Biased Lock

Biased Lock eliminates synchronization entirely for a thread that repeatedly acquires the same lock without contention.

It is advantageous when a lock is mostly accessed by a single thread, but becomes unnecessary under high contention.

13. Segment Lock

Segment Lock is used by ConcurrentHashMap , which divides the map into multiple segments, each protected by its own lock, allowing concurrent updates to different segments.

14. Mutex Lock

Mutex lock (mutual exclusion) ensures that only one thread can access a resource at a time; in Java it is represented by synchronized.

15. Synchronized Lock

synchronized

is a built‑in Java keyword that provides exclusive, reentrant, and unfair locking for methods or code blocks.

16. Deadlock

Deadlock occurs when two or more threads hold resources the others need, causing a circular wait with no progress.

Java threads cannot resolve deadlocks automatically; developers must design to avoid them.

17. Lock Coarsening

Lock Coarsening

expands the lock scope to cover a larger code block, reducing the frequency of lock/unlock operations and improving performance.

18. Lock Elimination

Lock Elimination

removes unnecessary synchronization when the JVM determines that an object does not escape the thread, treating it as thread‑local data.

Escape analysis is used to decide whether an object can be safely allocated on the stack.

19. synchronized Keyword

synchronized

is a Java keyword that provides exclusive, reentrant, and unfair locking for methods, static methods, or code blocks.

Instance method: locks the object instance (this).

Static method: locks the Class object.

Code block: locks the specified object.

20. Differences Between Lock and synchronized

Lock

is an interface offering explicit lock acquisition/release, manual handling of interruptions, and the ability to query lock status; synchronized is a language keyword with automatic release on exit and no interruption support.

Lock requires explicit lock() and unlock() calls.

Lock can be fair or unfair; synchronized is always unfair.

Lock supports multiple condition objects; synchronized does not.

21. ReentrantLock vs synchronized

ReentrantLock

is a Java class implementing the Lock interface, providing reentrant, exclusive, and fair/unfair locking with advanced features such as interruptible lock acquisition and multiple Condition objects.

Both Lock and synchronized ensure visibility and atomicity, but ReentrantLock offers greater flexibility and control.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaconcurrencySynchronizationLocks
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.