LockSupport

Learn how to use LockSupport for building higher-level locking constructs.

If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.

Overview

The LockSupport class is usually used as one of the building blocks for creating locks and synchronization classes. The class can’t be instantiated and offers static methods for use. These methods of the LockSupport class are designed to be used as tools for creating higher-level synchronization utilities, and are not in themselves useful for most concurrency control applications. The two methods offered by this class are park() and unpark() alongwith their variations. These methods provide low-level alternatives to the deprecated methods Thread.suspend() and Thread.resume().

park and unpark methods

The class associates a single permit with each thread that uses it. If the permit is not available the thread invoking park() is blocked. The blocked thread can subsequently be unblocked using the unpark() method by passing-in the blocked thread object as argument. If the permit is available, the thread invoking park() doesn’t block.

The official documentation suggests the idiomatic use of the LockSupport class’s park() method as follows:

    while (!canMoveForward()) {
        // ... other operations
        LockSupport.park(this);
    }

Locking or blocking isn’t used before the while loop or in the actions up until park() is invoked. Note that the park() method can experience spurious wake-ups and therefore, we need to check for the predicate again in a while loop.

Consider the snippet below, where the main thread unparks, i.e. makes the permit available and then parks, i.e. consumes the permit it just made available and moves forward. If the order of the two operations in the snippet is reversed, the main thread will be permanently blocked.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy