Java Concurrency Locks Explained: From Synchronized to ReentrantReadWriteLock

This article provides a comprehensive overview of Java concurrency locks, covering classifications such as optimistic, pessimistic, fair, unfair, reentrant, exclusive/shared, spin, and segmented locks, as well as detailed explanations of synchronized, ReentrantLock, and ReadWriteLock usage with code examples.

Java Interview Crash Guide
Java Interview Crash Guide
Java Interview Crash Guide
Java Concurrency Locks Explained: From Synchronized to ReentrantReadWriteLock

1. Types of Locks

Common lock categories include optimistic/pessimistic, fair/unfair, reentrant, exclusive/shared, mutex/read‑write, segmented, biased/lightweight/heavyweight, and spin locks.

1.1 Optimistic vs Pessimistic Locks

Optimistic locks assume no concurrent modification and validate at update time, often using version numbers or CAS. They suit read‑heavy workloads. Pessimistic locks assume contention and lock on each access, suitable for write‑heavy scenarios.

(1) Optimistic Lock

Implemented via lock‑free programming; CAS (Compare And Swap) reads a memory value V, compares with expected A, and writes B if equal.

Memory value V

Expected value A

New value B

Only when A equals V is V replaced by B; otherwise the operation returns the current V.

(2) Pessimistic Lock

Locks data on every read, causing other threads to block until the lock is released. Used in traditional relational databases (row/ table locks).

Pessimistic lock fits write‑intensive scenarios.

Optimistic lock fits read‑intensive scenarios.

1.2 Fair vs Unfair Locks

(1) Fair Lock

Threads acquire the lock in FIFO order, preventing starvation but reducing throughput.

(2) Unfair Lock

Threads try to acquire the lock immediately; if they fail they may retry, offering higher throughput but possible starvation.

(3) Typical Use

ReentrantLock can be created as fair (new ReentrantLock(true)) or unfair (default).

1.3 Exclusive vs Shared Locks

(1) Exclusive Lock

Only one thread may hold the lock at a time.

(2) Shared Lock

Multiple threads may hold the lock simultaneously.

In Java, ReentrantLock is exclusive, while ReadWriteLock provides a shared read lock and an exclusive write lock.

Read lock allows concurrent reads.

Write lock is exclusive.

(3) AQS

AbstractQueuedSynchronizer (AQS) is the foundation for building locks and synchronizers, using a volatile state and an internal FIFO queue.

1.4 Mutex vs Read‑Write Locks

Mutex (mutual exclusion) permits only one thread to access a resource, while read‑write locks allow many concurrent readers but exclusive writers.

(1) Mutex

Threads block when the lock is held.

(2) Read‑Write Lock

Multiple readers can proceed concurrently; writers obtain exclusive access.

(3) Linux Read‑Write Lock

pthread_mutex_init()
pthread_mutex_lock()
pthread_mutex_unlock()

pthread_rwlock_init()
pthread_rwlock_rdlock()
pthread_rwlock_wrlock()
pthread_rwlock_unlock()

pthread_cond_init()
pthread_cond_wait()
pthread_cond_signal()

1.5 Spin Lock

A spin lock repeatedly checks a lock variable until it becomes available, avoiding thread suspension but consuming CPU cycles.

(1) Java SpinLock Example

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

(2) Problems

If a thread holds the lock too long, other threads waste CPU in the spin loop.

The non‑fair implementation can cause thread starvation.

(3) Advantages

No context switch; thread stays active.

Faster than blocking locks when contention is low.

2. Design Patterns for Concurrent Locks

Lock designs include segmented locks, lock elimination, lock coarsening, polling/timed locks, and read‑write locks.

2.1 Segmented Lock

Used in ConcurrentHashMap; each segment is a ReentrantLock protecting a subset of buckets, allowing parallel updates to different segments.

2.2 Lock Elimination & Coarsening

JVM can remove unnecessary locks (elimination) or expand multiple fine‑grained locks into a single coarse lock (coarsening) based on escape analysis.

2.3 Polling & Timed Locks

Threads repeatedly attempt tryLock; tryLock can also accept a timeout to wait for a lock.

2.4 Read‑Write Lock

Implemented by ReentrantReadWriteLock, providing separate read and write locks.

ReadWriteLock lock = new ReentrantReadWriteLock();
Lock readLock = lock.readLock();
Lock writeLock = lock.writeLock();

3. Lock States in synchronized

synchronized uses monitorenter/monitorexit bytecode. Modern JVMs implement three lock states: biased, lightweight, and heavyweight, upgrading as contention increases.

No lock

Biased lock

Lightweight lock

Heavyweight lock

3.1 Biased, Lightweight, Heavyweight

Biased lock assumes a single thread; lightweight lock uses CAS and spinning when contention appears; heavyweight lock falls back to OS mutex, causing thread blocking.

3.2 Lock Upgrade

The JVM automatically upgrades or downgrades lock state based on runtime contention.

4. ReentrantLock

ReentrantLock is a re‑entrant mutual exclusion lock with richer features than synchronized.

4.1 Basic Usage

public class LockTest {
    private Lock lock = new ReentrantLock();
    public void testMethod() {
        lock.lock();
        for (int i = 0; i < 5; i++) {
            System.out.println("ThreadName=" + Thread.currentThread().getName() + " " + (i + 1));
        }
        lock.unlock();
    }
}

4.2 Condition

Condition enables multiple wait‑sets per lock, allowing selective notification unlike Object.notify.

4.3 Condition vs Object

await() ≈ wait()

signal() ≈ notify()

signalAll() ≈ notifyAll()

5. ReadWriteLock

ReadWriteLock solves performance bottlenecks in read‑heavy scenarios by allowing concurrent reads and exclusive writes.

5.1 Interface

public interface ReadWriteLock {
    Lock readLock();
    Lock writeLock();
}

5.2 ReentrantReadWriteLock Example

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Cache {
    static Map<String, Object> map = new HashMap<>();
    static ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    static Lock readLock = rwLock.readLock();
    static Lock writeLock = rwLock.writeLock();

    public static final Object getByKey(String key) {
        readLock.lock();
        try { return map.get(key); }
        finally { readLock.unlock(); }
    }

    public static final Object put(String key, Object value) {
        writeLock.lock();
        try { return map.put(key, value); }
        finally { writeLock.unlock(); }
    }
    // other methods omitted for brevity
}

5.3 Lock Downgrade

void processCachedData() {
    rwl.readLock().lock();
    if (!cacheValid) {
        rwl.readLock().unlock();
        rwl.writeLock().lock();
        try {
            if (!cacheValid) {
                data = ...;
                cacheValid = true;
            }
            rwl.readLock().lock(); // downgrade
        } finally {
            rwl.writeLock().unlock(); // still hold read lock
        }
    }
    try { use(data); } finally { rwl.readLock().unlock(); }
}
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.

JavaLocksReentrantLocksynchronizedReadWriteLock
Java Interview Crash Guide
Written by

Java Interview Crash Guide

Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.

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.