Comprehensive Overview of Java Locks: Fair, Unfair, Spin, Reentrant, Biased, Lightweight, Heavyweight, and More

This article provides a detailed explanation of various Java lock mechanisms—including fair and unfair locks, spin locks, lock elimination, lock coarsening, reentrant, class and object locks, biased, lightweight, heavyweight, pessimistic and optimistic locks—as well as practical code examples and a lock state table to help developers understand concurrency control in the JVM.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Comprehensive Overview of Java Locks: Fair, Unfair, Spin, Reentrant, Biased, Lightweight, Heavyweight, and More

When learning or using Java, developers encounter many lock concepts such as fair lock, non‑fair lock, spin lock, reentrant lock, biased lock, lightweight lock, heavyweight lock, read‑write lock, and mutex lock. This article organizes these Java locks and invites discussion.

Fair and Non‑Fair Locks

A fair lock grants access to waiting threads in the order they requested the lock, preventing starvation but reducing overall throughput. A non‑fair lock allows a thread to acquire the lock immediately if it becomes available, improving performance at the risk of starvation. Fair locks can be created with new ReentrantLock(true).

Spin Lock

Because Java threads map to native OS threads, blocking or waking a thread requires a transition from user mode to kernel mode, which is costly. When lock hold times are very short, it is more efficient for a thread to busy‑wait (spin) rather than incur a context switch. Spin locks are introduced in JDK 1.4.2 (enabled with -XX:+UseSpinning) and become adaptive in JDK 6, adjusting spin duration based on previous lock behavior.

Lock Elimination

The JIT compiler can remove locks that are proven unnecessary through escape analysis. If an object does not escape the current thread, its synchronization can be eliminated because the object is effectively thread‑local.

public String concatString(String s1, String s2, String s3) {
    StringBuffer sb = new StringBuffer();
    sb.append(s1);
    sb.append(s2);
    sb.append(s3);
    return sb.toString();
}

Since sb does not escape the method, the synchronized append calls can be removed after JIT compilation.

Lock Coarsening

When a series of operations repeatedly lock and unlock the same object (e.g., multiple append calls on a shared StringBuffer), the JVM may expand the lock scope to cover the whole sequence, reducing the number of lock/unlock operations.

Reentrant Lock

Also known as a recursive lock, a reentrant lock allows the same thread to acquire the same lock multiple times without deadlocking. In Java, both ReentrantLock and synchronized are reentrant.

Class Lock vs. Object Lock

public class LockStrategy {
    public Object object1 = new Object();
    public static synchronized void method1() {}
    public void method2() { synchronized(LockStrategy.class) {} }
    public synchronized void method4() {}
    public void method5() { synchronized(this) {} }
    public void method6() { synchronized(object1) {} }
}

Static synchronized methods and synchronized(LockStrategy.class) use a class‑level lock, while instance synchronized methods and synchronized(this) or synchronized(object1) use object‑level locks.

Exercise: Given two instances a and b of the following class, which method pairs can be accessed concurrently by more than one thread?

public class SynchronizedTest {
    public synchronized void method1() {}
    public synchronized void method2() {}
    public static synchronized void method3() {}
    public static synchronized void method4() {}
}

Answer: B and E.

Biased, Lightweight, and Heavyweight Locks

These lock states are represented in the object header’s Mark Word. The table below shows the lock state, stored content, and flag bits.

Lock State

Stored Content

Flag Bits

No Lock

hashCode, age, biased‑lock flag (0)

01

Lightweight

pointer to stack lock record

00

Heavyweight

pointer to monitor (mutex)

10

GC Mark

(empty)

11

Biased Lock

biased thread ID, timestamp, age, biased flag (1)

01

Biased locks, introduced in JDK 6, eliminate synchronization overhead when a lock is uncontended by a single thread. If contention occurs, the lock may be revoked and upgraded to a lightweight or heavyweight lock.

The JVM acquires a lock by copying the Mark Word to a thread‑local lock record, then using CAS to replace the Mark Word with a pointer to that record. Failure triggers spinning, possible upgrade to lightweight, and finally heavyweight if spinning fails.

Pessimistic vs. Optimistic Lock

Pessimistic locking assumes conflicts and blocks other operations, while optimistic locking assumes no conflict and checks for violations only at commit time (often using version numbers or timestamps).

Shared vs. Exclusive Lock

Shared locks allow multiple transactions to read a resource simultaneously; exclusive locks allow a single transaction to both read and write.

Read‑Write Lock

Implemented in Java via ReentrantReadWriteLock, it permits multiple concurrent readers or a single writer.

Mutex Lock

Only one thread may hold the lock at a time; in Java, synchronized and JUC Lock implementations are mutexes.

No Lock

Code that does not share mutable state does not need synchronization. Techniques include stateless programming, thread‑local storage, volatile, CAS, and coroutines.

References:

《深入理解Java虚拟机》周志明著

《Java并发编程的艺术》方腾飞等著

Java对象大小内幕浅析

JVM内部细节之一:synchronized关键字及实现细节(轻量级锁)

JVM内部细节之二:偏向锁(Biased Locking)

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.

JavaJVMconcurrencySynchronizationmultithreadingLocks
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

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.