Fundamentals 15 min read

Classification and Implementation of Various Java Locks

This article explains the different types of Java locks—including fair, reentrant, exclusive, read‑write, optimistic, pessimistic, segment, biased, lightweight, heavyweight, and spin locks—describes their characteristics, usage scenarios, and provides concrete code examples for each implementation.

Java Captain
Java Captain
Java Captain
Classification and Implementation of Various Java Locks

This article introduces a comprehensive classification of Java concurrency locks, starting with fair and non‑fair locks, where a fair lock grants access in request order while a non‑fair lock may allow later requests to acquire the lock first, affecting throughput and potential starvation.

It then distinguishes reentrant locks, which allow the same thread to acquire the lock multiple times without deadlock, from non‑reentrant locks that cannot be recursively acquired. The ReentrantLock and synchronized constructs are examples of reentrant locks, while a custom spin‑based lock demonstrates non‑reentrancy.

public void setA() throws Exception {
    Thread.sleep(1000);
    setB();
}

public void setB() throws Exception {
    Thread.sleep(1000);
}

A simple non‑reentrant lock implementation using AtomicReference is shown, followed by a modification that adds a counter to make it reentrant.

class UnreentrantLock {
    private AtomicReference
owner = new AtomicReference<>();
    public void lock() {
        Thread current = Thread.currentThread();
        while (!owner.compareAndSet(null, current)) {
            // spin
        }
    }
    public void unlock() {
        Thread current = Thread.currentThread();
        owner.compareAndSet(current, null);
    }
}

The article explains exclusive (single‑thread) versus shared locks, noting that ReentrantReadWriteLock provides a shared read lock and an exclusive write lock, enabling high‑concurrency reads while writes remain mutually exclusive.

It covers mutex locks that block other threads until release, and read‑write locks that allow multiple concurrent readers but only one writer, describing their three states: unlocked, read‑locked, and write‑locked.

Optimistic and pessimistic locking strategies are compared: pessimistic locks assume conflicts and lock resources preemptively (e.g., synchronized , ReentrantLock ), while optimistic locks assume no conflict and validate at commit time using version numbers or CAS operations, as seen in Java’s atomic classes.

Segment locks are introduced as a design pattern used by ConcurrentHashMap , where the map is divided into segments each protected by its own lock, dramatically reducing contention and allowing many concurrent writes.

The JVM‑level lock states—biased, lightweight, and heavyweight—are described as optimizations for synchronized blocks that evolve based on contention, without being Java language constructs.

Spin locks are detailed, starting with a brief review of the CAS (Compare‑And‑Swap) algorithm, then presenting a basic spin‑lock implementation and a reentrant spin‑lock that tracks acquisition count.

public class SpinLock {
    private AtomicReference
cas = new AtomicReference<>();
    public void lock() {
        Thread current = Thread.currentThread();
        while (!cas.compareAndSet(null, current)) {
            // spin
        }
    }
    public void unlock() {
        Thread current = Thread.currentThread();
        cas.compareAndSet(current, null);
    }
}

Finally, the article summarizes the advantages and drawbacks of spin locks, noting their low context‑switch overhead but potential CPU waste and lack of fairness, and shows how to extend them to support reentrancy.

JavaConcurrencyLocksAQSReentrantLockspinlock
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login 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.