In Java, the term "park" refers to a method of blocking a thread, making it inactive until some condition is met or an event occurs. This is part of the concurrency design in Java and is primarily associated with the LockSupport class, which provides the park() and unpark() methods.
Key Concepts:
-
Parked State:
- When a thread calls
LockSupport.park(), it is effectively put into a "parked" state. This means the thread is not actively running and is waiting for notification to wake up.
- It's important to note that in the parked state, the thread can still be scheduled by the Java Virtual Machine (JVM), but it isn't executing any code.
-
Unparked State:
- A thread can be "unparked" using
LockSupport.unpark(Thread thread), where the specified thread is made runnable and can continue executing.
- The unpark method will release the thread from its parked state, allowing it to proceed with its execution.
-
Purpose of Park and Unpark:
- The main functionality of parking and unparking threads is to provide a mechanism for synchronization without using more heavyweight constructs like
wait(), notify(), or higher-level synchronization primitives like synchronized blocks or explicit locks.
- This can be particularly useful for implementing custom thread-scheduling algorithms or non-blocking data structures.
Usage Scenario Example:
import java.util.concurrent.locks.LockSupport;
public class ParkExample {
public static void main(String[] args) throws InterruptedException {
Thread workerThread = new Thread(() -> {
System.out.println("Worker thread is parking...");
// Park the thread
LockSupport.park();
System.out.println("Worker thread is unparked and resumes.");
});
workerThread.start();
Thread.sleep(1000); // Main thread sleeps for a while
System.out.println("Main thread un-parking worker thread...");
// Unpark the worker thread
LockSupport.unpark(workerThread);
}
}
Important Notes:
- Interruptions: Unlike blocking methods such as
Object.wait() or Thread.sleep(), parking a thread does not consider its interrupted status. If a parked thread needs to respond to interruption, it must be checked later.
- Native Support: The park and unpark methods leverage low-level OS capabilities for managing thread states, making them generally more efficient than other higher-level synchronization mechanisms.
- LockSupport: It is a utility that provides the fundamental operations for blocking and unblocking threads, and is often used under the hood by various Java concurrency utilities, such as
ReentrantLock and java.util.concurrent collections.
The key takeaway is that the "park" status in the context of Java threads refers to a state where a thread is suspended and waits until it is explicitly allowed to continue (unparked), providing a flexible way to manage thread coordination.