skip to content

AQS & LockSupport

AbstractQueuedSynchronizer is the state and wait queue under ReentrantLock, Semaphore and CountDownLatch, and LockSupport parks its threads. Interviewers ask it to test how locks really block.

part ofJavaread it →
on this pageshow

questions

2

What do Java's LockSupport.park() and unpark() do, what happens when unpark comes first, and how do they differ from Object.wait() and notify()?

level: middleimportance: should knowfreq 40%

answer

  1. one per thread, never more
  2. park consumes, unpark grants
  3. early unpark is not lost
  4. no monitor, no checked exception
  5. recheck the condition in a loop

basics

~20 s

LockSupport.park() returns at once if the thread's single permit is available, consuming it, and otherwise may block; unpark(thread) makes that permit available. An unpark that comes first is remembered. Unlike wait and notify, neither needs a monitor.

solid answer

~40 s

`LockSupport` associates one permit with each thread. `LockSupport.park()` consumes the permit and returns at once if it is available; otherwise the thread goes dormant until another thread calls `unpark` on it, it is interrupted, or the call returns spuriously, so it belongs in a loop that rechecks a condition. `unpark(thread)` makes the permit available, so an `unpark` that comes first is not lost: the next `park` returns immediately. Permits do not accumulate, so two `unpark` calls still pay for only one `park`. Unlike `Object.wait()` and `notify()`, `park` needs no monitor and releases none, `unpark` names the exact thread rather than an arbitrary waiter, and an interrupt makes `park` return without an `InterruptedException`, leaving the interrupted status set.

code

java · 27 lines
java
import java.util.concurrent.locks.LockSupport;

final class Gate {
    private final Thread waiter;
    private volatile boolean open;

    Gate(Thread waiter) { this.waiter = waiter; }

    // Called only by the waiter thread.
    void await() {
        boolean interrupted = false;
        while (!open) {                        // park may return for no reason
            LockSupport.park(this);
            if (Thread.interrupted()) {        // a set status makes park return at once
                interrupted = true;
            }
        }
        if (interrupted) {
            Thread.currentThread().interrupt(); // restore for the caller
        }
    }

    void open() {
        open = true;                  // publish before waking
        LockSupport.unpark(waiter);   // safe even if the waiter has not parked yet
    }
}

go deeper

for a junior

Recall that park pauses the current thread and unpark names a thread to resume, through a single permit. Most code uses locks and queues built on these calls, not the calls themselves.

for a middle

Explain the permit: it makes unpark before park safe, it never counts past one, and park can return for no reason, so the call sits in a loop over a volatile condition.

for a senior

Read parked threads in a thread dump: they show WAITING or TIMED_WAITING, with a blocker if one was passed, not BLOCKED on a monitor. Pass one yourself, handle the interrupted status, and watch for loops that spin because the status stays set.

for a principal

Decide where these primitives may live. They are tools for building synchronizers, so a sensible team default keeps direct use out of application code and confines it to reviewed infrastructure, with java.util.concurrent classes everywhere else.

## What LockSupport is `java.util.concurrent.locks.LockSupport`, available since Java 1.5, holds the basic thread-blocking primitives used to build locks and other synchronizers. Its documentation calls them tools for higher-level utilities, not in themselves useful for most concurrency control. `AbstractQueuedSynchronizer`, the base of `ReentrantLock` and `Semaphore`, blocks its queued threads with `LockSupport.park(this)` and wakes them with `LockSupport.unpark`. ## The single permit Each thread that uses `LockSupport` has one **permit**, in the sense of a `Semaphore` permit but with a ceiling: - **`park()`**: if the permit is available, it is consumed and the call returns at once. Otherwise the thread may block. - **`unpark(thread)`**: makes that thread's permit available if it was not already. A thread blocked in `park` unblocks; otherwise its next `park` is guaranteed not to block. - **No accumulation**: there is at most one permit. After two `unpark` calls, the first `park` returns at once and the second may block. - **Edge cases**: `unpark(null)` has no effect, and `unpark` on a thread not yet started is not guaranteed to have any effect. So **an early `unpark` is not lost**. A race where `unpark` arrives just before `park` still preserves liveness, because the permit remembers it. That is what the permit is for. ## Why park sits in a loop A parked thread lies dormant until one of these happens, and `park` does not report which: 1. Another thread calls `unpark` on it. 2. Another thread interrupts it. 3. The call returns **spuriously**, for no reason. `parkNanos` and `parkUntil` add a fourth: the time limit passes. So the documentation gives one form of use, a loop that rechecks a condition: ```java while (!canProceed()) { // ensure request to unpark is visible to other threads LockSupport.park(this); } ``` Reliable use requires a `volatile` or atomic variable to control when to park and unpark, because the order of these calls is maintained with respect to those accesses, but not necessarily with respect to non-volatile ones. Interrupts need care. `park` declares no checked exception. It returns with the interrupted status still set, and while that status is set, later `park` calls also return immediately, so an uninterruptible loop that ignores it can spin. Clear it with `Thread.interrupted()`, remember that it happened, and restore it on the way out. ## Compared with wait and notify A **monitor** is the lock behind `synchronized`, and `Object.wait()` and `notify()` work through it. | Aspect | `LockSupport.park` and `unpark` | `Object.wait` and `notify` | |---|---|---| | Monitor required | none | caller must own it, else `IllegalMonitorStateException` | | Monitors released | none | that object's monitor; any others stay held | | Who is woken | the named thread | one arbitrary waiter, or all with `notifyAll` | | Signal with no waiter | kept as the permit | no effect on a later `wait` | | On interrupt | returns, status stays set | throws `InterruptedException`, status cleared | | Spurious returns | possible | possible | | Thread state | `WAITING`, or `TIMED_WAITING` when timed | `WAITING`, or `TIMED_WAITING` when timed | ## Traps - **Parking while holding a monitor.** `park` releases nothing, so threads entering that `synchronized` block stay `BLOCKED`, and the thread meant to call `unpark` may be one of them. - **Lost unpark.** The permit belongs to the thread, not to one wait. If anything between publishing the request and calling `park` also parks, including implicitly through class loading, it can consume the permit and leave the thread unresponsive. The documentation's sample mutex loads `LockSupport` early to reduce that risk. - **No blocker.** The forms `park(Object)`, `parkNanos(Object, long)` and `parkUntil(Object, long)` record the object a thread is waiting on for diagnostic tools, which can read it through `LockSupport.getBlocker(Thread)`. The documentation strongly encourages them, and `this` is the normal argument inside a lock. - **Time arguments.** `parkNanos` takes a relative number of nanoseconds and does nothing if it is zero or negative, while `parkUntil` takes an absolute time in milliseconds from the Epoch. ## Virtual threads `park` branches on `Thread.isVirtual()`. Virtual threads previewed in JDK 19 and became final in JDK 21, and parking one releases its underlying platform thread, which is how locks and queues built on `LockSupport` work with them. If the virtual thread is pinned, JDK 27's source parks it on its carrier instead. This is not a difference from `wait` at JDK 25 or 27: since JDK 24, JEP 491 has `Object.wait()` unmount a virtual thread as well.

  • Why must LockSupport.park() be called in a loop?
    It may return at any time for no reason, and it does not report why it returned. The caller can test the interrupted status, but nothing from park separates an unpark from a spurious return. So the caller rechecks its condition after every return, and that condition should be a volatile or atomic variable, because the documentation ties reliable ordering of these calls to such accesses.
  • What is a lost unpark, if the permit exists to remember an early LockSupport.unpark()?
    The permit belongs to the thread, not to one particular wait. If something between publishing the wait request and calling park also parks, such as taking a lock or class loading, it can consume the permit. The thread then parks with none left and may stay unresponsive. The documentation therefore designs park for use only where nothing in that window locks or blocks.
  • What does the blocker argument in LockSupport.park(Object) do?
    It records the object the thread is waiting on while it is parked, so monitoring and diagnostic tools can identify why it is blocked, and LockSupport.getBlocker(Thread) returns it. It does not change how the thread blocks. AbstractQueuedSynchronizer passes itself, so a thread queued on a ReentrantLock reports that lock's Sync object as its blocker.

A permit works like the flag on a mailbox: the carrier can raise it whether or not you are standing there, raising it twice still shows one flag, and you lower it when you check. Object.notify() is more like calling out in a room: only someone already there hears it.

  • Two unpark calls let the next two park calls return immediately.
  • An unpark that arrives before park is lost, like a notify with no waiter.
  • LockSupport.park must be called while holding a monitor or a lock.
  • LockSupport.park throws InterruptedException when the thread is interrupted.
  • A return from park proves that another thread called unpark.
  • LockSupport.park releases the monitors the thread holds, the way wait does.

LockSupport park and unpark
Java 1.5

Assumes JDK 27; the virtual-thread path of LockSupport.park has been final since JDK 21, and the permit behaviour itself dates from Java 1.5.

context

open as a page

What is Java's AbstractQueuedSynchronizer, how do ReentrantLock and Semaphore map onto its state, and when would you subclass it?

level: middleimportance: should knowfreq 48%

basics

~20 s

AbstractQueuedSynchronizer is the framework under ReentrantLock and Semaphore: one atomic int state whose meaning the subclass defines, plus a FIFO queue of waiting threads. Subclass it only when no existing synchronizer gives the acquire and release rules you need.

open as a page