2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation. Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
31 * Written by Doug Lea with assistance from members of JCP JSR-166
32 * Expert Group and released to the public domain, as explained at
33 * http://creativecommons.org/publicdomain/zero/1.0/
36 package java.util.concurrent.locks;
37 import java.util.concurrent.*;
38 import sun.misc.Unsafe;
42 * Basic thread blocking primitives for creating locks and other
43 * synchronization classes.
45 * <p>This class associates, with each thread that uses it, a permit
46 * (in the sense of the {@link java.util.concurrent.Semaphore
47 * Semaphore} class). A call to {@code park} will return immediately
48 * if the permit is available, consuming it in the process; otherwise
49 * it <em>may</em> block. A call to {@code unpark} makes the permit
50 * available, if it was not already available. (Unlike with Semaphores
51 * though, permits do not accumulate. There is at most one.)
53 * <p>Methods {@code park} and {@code unpark} provide efficient
54 * means of blocking and unblocking threads that do not encounter the
55 * problems that cause the deprecated methods {@code Thread.suspend}
56 * and {@code Thread.resume} to be unusable for such purposes: Races
57 * between one thread invoking {@code park} and another thread trying
58 * to {@code unpark} it will preserve liveness, due to the
59 * permit. Additionally, {@code park} will return if the caller's
60 * thread was interrupted, and timeout versions are supported. The
61 * {@code park} method may also return at any other time, for "no
62 * reason", so in general must be invoked within a loop that rechecks
63 * conditions upon return. In this sense {@code park} serves as an
64 * optimization of a "busy wait" that does not waste as much time
65 * spinning, but must be paired with an {@code unpark} to be
68 * <p>The three forms of {@code park} each also support a
69 * {@code blocker} object parameter. This object is recorded while
70 * the thread is blocked to permit monitoring and diagnostic tools to
71 * identify the reasons that threads are blocked. (Such tools may
72 * access blockers using method {@link #getBlocker}.) The use of these
73 * forms rather than the original forms without this parameter is
74 * strongly encouraged. The normal argument to supply as a
75 * {@code blocker} within a lock implementation is {@code this}.
77 * <p>These methods are designed to be used as tools for creating
78 * higher-level synchronization utilities, and are not in themselves
79 * useful for most concurrency control applications. The {@code park}
80 * method is designed for use only in constructions of the form:
81 * <pre>while (!canProceed()) { ... LockSupport.park(this); }</pre>
82 * where neither {@code canProceed} nor any other actions prior to the
83 * call to {@code park} entail locking or blocking. Because only one
84 * permit is associated with each thread, any intermediary uses of
85 * {@code park} could interfere with its intended effects.
87 * <p><b>Sample Usage.</b> Here is a sketch of a first-in-first-out
88 * non-reentrant lock class:
91 * private final AtomicBoolean locked = new AtomicBoolean(false);
92 * private final Queue<Thread> waiters
93 * = new ConcurrentLinkedQueue<Thread>();
95 * public void lock() {
96 * boolean wasInterrupted = false;
97 * Thread current = Thread.currentThread();
98 * waiters.add(current);
100 * // Block while not first in queue or cannot acquire lock
101 * while (waiters.peek() != current ||
102 * !locked.compareAndSet(false, true)) {
103 * LockSupport.park(this);
104 * if (Thread.interrupted()) // ignore interrupts while waiting
105 * wasInterrupted = true;
109 * if (wasInterrupted) // reassert interrupt status on exit
110 * current.interrupt();
113 * public void unlock() {
115 * LockSupport.unpark(waiters.peek());
120 public class LockSupport {
121 private LockSupport() {} // Cannot be instantiated.
123 // Hotspot implementation via intrinsics API
124 private static final Unsafe unsafe = Unsafe.getUnsafe();
125 private static final long parkBlockerOffset;
129 parkBlockerOffset = unsafe.objectFieldOffset
130 (java.lang.Thread.class.getDeclaredField("parkBlocker"));
131 } catch (Exception ex) { throw new Error(ex); }
134 private static void setBlocker(Thread t, Object arg) {
135 // Even though volatile, hotspot doesn't need a write barrier here.
136 unsafe.putObject(t, parkBlockerOffset, arg);
140 * Makes available the permit for the given thread, if it
141 * was not already available. If the thread was blocked on
142 * {@code park} then it will unblock. Otherwise, its next call
143 * to {@code park} is guaranteed not to block. This operation
144 * is not guaranteed to have any effect at all if the given
145 * thread has not been started.
147 * @param thread the thread to unpark, or {@code null}, in which case
148 * this operation has no effect
150 public static void unpark(Thread thread) {
152 unsafe.unpark(thread);
156 * Disables the current thread for thread scheduling purposes unless the
157 * permit is available.
159 * <p>If the permit is available then it is consumed and the call returns
160 * immediately; otherwise
161 * the current thread becomes disabled for thread scheduling
162 * purposes and lies dormant until one of three things happens:
165 * <li>Some other thread invokes {@link #unpark unpark} with the
166 * current thread as the target; or
168 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
169 * the current thread; or
171 * <li>The call spuriously (that is, for no reason) returns.
174 * <p>This method does <em>not</em> report which of these caused the
175 * method to return. Callers should re-check the conditions which caused
176 * the thread to park in the first place. Callers may also determine,
177 * for example, the interrupt status of the thread upon return.
179 * @param blocker the synchronization object responsible for this
183 public static void park(Object blocker) {
184 Thread t = Thread.currentThread();
185 setBlocker(t, blocker);
186 unsafe.park(false, 0L);
191 * Disables the current thread for thread scheduling purposes, for up to
192 * the specified waiting time, unless the permit is available.
194 * <p>If the permit is available then it is consumed and the call
195 * returns immediately; otherwise the current thread becomes disabled
196 * for thread scheduling purposes and lies dormant until one of four
200 * <li>Some other thread invokes {@link #unpark unpark} with the
201 * current thread as the target; or
203 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
204 * the current thread; or
206 * <li>The specified waiting time elapses; or
208 * <li>The call spuriously (that is, for no reason) returns.
211 * <p>This method does <em>not</em> report which of these caused the
212 * method to return. Callers should re-check the conditions which caused
213 * the thread to park in the first place. Callers may also determine,
214 * for example, the interrupt status of the thread, or the elapsed time
217 * @param blocker the synchronization object responsible for this
219 * @param nanos the maximum number of nanoseconds to wait
222 public static void parkNanos(Object blocker, long nanos) {
224 Thread t = Thread.currentThread();
225 setBlocker(t, blocker);
226 unsafe.park(false, nanos);
232 * Disables the current thread for thread scheduling purposes, until
233 * the specified deadline, unless the permit is available.
235 * <p>If the permit is available then it is consumed and the call
236 * returns immediately; otherwise the current thread becomes disabled
237 * for thread scheduling purposes and lies dormant until one of four
241 * <li>Some other thread invokes {@link #unpark unpark} with the
242 * current thread as the target; or
244 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
247 * <li>The specified deadline passes; or
249 * <li>The call spuriously (that is, for no reason) returns.
252 * <p>This method does <em>not</em> report which of these caused the
253 * method to return. Callers should re-check the conditions which caused
254 * the thread to park in the first place. Callers may also determine,
255 * for example, the interrupt status of the thread, or the current time
258 * @param blocker the synchronization object responsible for this
260 * @param deadline the absolute time, in milliseconds from the Epoch,
264 public static void parkUntil(Object blocker, long deadline) {
265 Thread t = Thread.currentThread();
266 setBlocker(t, blocker);
267 unsafe.park(true, deadline);
272 * Returns the blocker object supplied to the most recent
273 * invocation of a park method that has not yet unblocked, or null
274 * if not blocked. The value returned is just a momentary
275 * snapshot -- the thread may have since unblocked or blocked on a
276 * different blocker object.
278 * @param t the thread
279 * @return the blocker
280 * @throws NullPointerException if argument is null
283 public static Object getBlocker(Thread t) {
285 throw new NullPointerException();
286 return unsafe.getObjectVolatile(t, parkBlockerOffset);
290 * Disables the current thread for thread scheduling purposes unless the
291 * permit is available.
293 * <p>If the permit is available then it is consumed and the call
294 * returns immediately; otherwise the current thread becomes disabled
295 * for thread scheduling purposes and lies dormant until one of three
300 * <li>Some other thread invokes {@link #unpark unpark} with the
301 * current thread as the target; or
303 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
304 * the current thread; or
306 * <li>The call spuriously (that is, for no reason) returns.
309 * <p>This method does <em>not</em> report which of these caused the
310 * method to return. Callers should re-check the conditions which caused
311 * the thread to park in the first place. Callers may also determine,
312 * for example, the interrupt status of the thread upon return.
314 public static void park() {
315 unsafe.park(false, 0L);
319 * Disables the current thread for thread scheduling purposes, for up to
320 * the specified waiting time, unless the permit is available.
322 * <p>If the permit is available then it is consumed and the call
323 * returns immediately; otherwise the current thread becomes disabled
324 * for thread scheduling purposes and lies dormant until one of four
328 * <li>Some other thread invokes {@link #unpark unpark} with the
329 * current thread as the target; or
331 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
332 * the current thread; or
334 * <li>The specified waiting time elapses; or
336 * <li>The call spuriously (that is, for no reason) returns.
339 * <p>This method does <em>not</em> report which of these caused the
340 * method to return. Callers should re-check the conditions which caused
341 * the thread to park in the first place. Callers may also determine,
342 * for example, the interrupt status of the thread, or the elapsed time
345 * @param nanos the maximum number of nanoseconds to wait
347 public static void parkNanos(long nanos) {
349 unsafe.park(false, nanos);
353 * Disables the current thread for thread scheduling purposes, until
354 * the specified deadline, unless the permit is available.
356 * <p>If the permit is available then it is consumed and the call
357 * returns immediately; otherwise the current thread becomes disabled
358 * for thread scheduling purposes and lies dormant until one of four
362 * <li>Some other thread invokes {@link #unpark unpark} with the
363 * current thread as the target; or
365 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
366 * the current thread; or
368 * <li>The specified deadline passes; or
370 * <li>The call spuriously (that is, for no reason) returns.
373 * <p>This method does <em>not</em> report which of these caused the
374 * method to return. Callers should re-check the conditions which caused
375 * the thread to park in the first place. Callers may also determine,
376 * for example, the interrupt status of the thread, or the current time
379 * @param deadline the absolute time, in milliseconds from the Epoch,
382 public static void parkUntil(long deadline) {
383 unsafe.park(true, deadline);