Video in progress

Strong Middle 🧵 Concurrency

How does LockSupport.park/unpark work, and how do locks like ReentrantLock rely on it internally?

park() puts the current thread to sleep until a "permit" is available, and unpark(t) hands that thread one permit. AQS, which sits under ReentrantLock, Semaphore and CountDownLatch, changes its state with CAS, queues the waiters, and puts them to sleep and wakes them with exactly park/unpark.

📖 Answer

LockSupport is the lowest layer of java.util.concurrent. Every thread has a single "permit", and it doesn't accumulate: it's either 0 or 1.

Thread waiter = Thread.ofPlatform().start(() -> {
    System.out.println("uxlayman");
    LockSupport.park();            // no permit: goes to sleep
    System.out.println("uyg'ondim");
});

Thread.sleep(100);
LockSupport.unpark(waiter);        // hand out the permit

The difference from wait/notify: no monitor is needed, and if unpark is called before park, the signal isn't lost. The next park() returns immediately. The classic bug of "the notify already went by and nobody will ever wake me" doesn't exist here.

But park() can return for no reason at all, and on interrupt it doesn't throw, it just returns. So you always call it inside a loop and recheck the condition.

AQS (AbstractQueuedSynchronizer) is built on top of this:

  • one volatile int state: the reentry count in ReentrantLock, the number of permits in Semaphore, the remaining count in CountDownLatch;
  • it first tries to grab state with CAS, so with no contention the thread never sleeps at all;
  • if that fails, the thread is added to a wait queue (a linked list in the CLH style) and parked;
  • when the lock is released, the thread at the head of the queue is woken with unpark.

The WAITING (parking) and parking to wait for <0x...> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) lines in a thread dump are exactly this mechanism. You rarely use LockSupport directly in your own code, but knowing it helps a lot when you read a dump.