1 /*
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
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.
9 *
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).
15 *
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.
19 *
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
22 * questions.
23 */
24
25 /*
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
29 * file:
30 *
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/
34 */
35
36 package java.util.concurrent.locks;
37
38 import jdk.internal.misc.Unsafe;
39
40 /**
41 * Basic thread blocking primitives for creating locks and other
42 * synchronization classes.
43 *
44 * <p>This class associates, with each thread that uses it, a permit
45 * (in the sense of the {@link java.util.concurrent.Semaphore
46 * Semaphore} class). A call to {@code park} will return immediately
47 * if the permit is available, consuming it in the process; otherwise
48 * it <em>may</em> block. A call to {@code unpark} makes the permit
49 * available, if it was not already available. (Unlike with Semaphores
50 * though, permits do not accumulate. There is at most one.)
51 * Reliable usage requires the use of volatile (or atomic) variables
52 * to control when to park or unpark. Orderings of calls to these
53 * methods are maintained with respect to volatile variable accesses,
54 * but not necessarily non-volatile variable accesses.
55 *
56 * <p>Methods {@code park} and {@code unpark} provide efficient
57 * means of blocking and unblocking threads that do not encounter the
58 * problems that cause the deprecated methods {@code Thread.suspend}
59 * and {@code Thread.resume} to be unusable for such purposes: Races
60 * between one thread invoking {@code park} and another thread trying
61 * to {@code unpark} it will preserve liveness, due to the
62 * permit. Additionally, {@code park} will return if the caller's
63 * thread was interrupted, and timeout versions are supported. The
64 * {@code park} method may also return at any other time, for "no
65 * reason", so in general must be invoked within a loop that rechecks
66 * conditions upon return. In this sense {@code park} serves as an
67 * optimization of a "busy wait" that does not waste as much time
68 * spinning, but must be paired with an {@code unpark} to be
69 * effective.
70 *
71 * <p>The three forms of {@code park} each also support a
72 * {@code blocker} object parameter. This object is recorded while
73 * the thread is blocked to permit monitoring and diagnostic tools to
74 * identify the reasons that threads are blocked. (Such tools may
75 * access blockers using method {@link #getBlocker(Thread)}.)
76 * The use of these forms rather than the original forms without this
77 * parameter is strongly encouraged. The normal argument to supply as
78 * a {@code blocker} within a lock implementation is {@code this}.
79 *
80 * <p>These methods are designed to be used as tools for creating
81 * higher-level synchronization utilities, and are not in themselves
82 * useful for most concurrency control applications. The {@code park}
83 * method is designed for use only in constructions of the form:
84 *
85 * <pre> {@code
86 * while (!canProceed()) {
87 * // ensure request to unpark is visible to other threads
88 * ...
89 * LockSupport.park(this);
90 * }}</pre>
91 *
92 * where no actions by the thread publishing a request to unpark,
93 * prior to the call to {@code park}, entail locking or blocking.
94 * Because only one permit is associated with each thread, any
95 * intermediary uses of {@code park}, including implicitly via class
96 * loading, could lead to an unresponsive thread (a "lost unpark").
97 *
98 * <p><b>Sample Usage.</b> Here is a sketch of a first-in-first-out
99 * non-reentrant lock class:
100 * <pre> {@code
101 * class FIFOMutex {
102 * private final AtomicBoolean locked = new AtomicBoolean(false);
103 * private final Queue<Thread> waiters
104 * = new ConcurrentLinkedQueue<>();
105 *
106 * public void lock() {
107 * boolean wasInterrupted = false;
108 * // publish current thread for unparkers
109 * waiters.add(Thread.currentThread());
110 *
111 * // Block while not first in queue or cannot acquire lock
112 * while (waiters.peek() != Thread.currentThread() ||
113 * !locked.compareAndSet(false, true)) {
114 * LockSupport.park(this);
115 * // ignore interrupts while waiting
116 * if (Thread.interrupted())
117 * wasInterrupted = true;
118 * }
119 *
120 * waiters.remove();
121 * // ensure correct interrupt status on return
122 * if (wasInterrupted)
123 * Thread.currentThread().interrupt();
124 * }
125 *
126 * public void unlock() {
127 * locked.set(false);
128 * LockSupport.unpark(waiters.peek());
129 * }
130 *
131 * static {
132 * // Reduce the risk of "lost unpark" due to classloading
133 * Class<?> ensureLoaded = LockSupport.class;
134 * }
135 * }}</pre>
136 *
137 * @since 1.5
138 */
139 public class LockSupport {
140 private LockSupport() {} // Cannot be instantiated.
141
142 private static void setBlocker(Thread t, Object arg) {
143 // Even though volatile, hotspot doesn't need a write barrier here.
144 U.putObject(t, PARKBLOCKER, arg);
145 }
146
147 /**
148 * Makes available the permit for the given thread, if it
149 * was not already available. If the thread was blocked on
150 * {@code park} then it will unblock. Otherwise, its next call
151 * to {@code park} is guaranteed not to block. This operation
152 * is not guaranteed to have any effect at all if the given
153 * thread has not been started.
154 *
155 * @param thread the thread to unpark, or {@code null}, in which case
156 * this operation has no effect
157 */
158 public static void unpark(Thread thread) {
159 if (thread != null)
160 U.unpark(thread);
161 }
162
163 /**
164 * Disables the current thread for thread scheduling purposes unless the
165 * permit is available.
166 *
167 * <p>If the permit is available then it is consumed and the call returns
168 * immediately; otherwise
169 * the current thread becomes disabled for thread scheduling
170 * purposes and lies dormant until one of three things happens:
171 *
172 * <ul>
173 * <li>Some other thread invokes {@link #unpark unpark} with the
174 * current thread as the target; or
175 *
176 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
177 * the current thread; or
178 *
179 * <li>The call spuriously (that is, for no reason) returns.
180 * </ul>
181 *
182 * <p>This method does <em>not</em> report which of these caused the
183 * method to return. Callers should re-check the conditions which caused
184 * the thread to park in the first place. Callers may also determine,
185 * for example, the interrupt status of the thread upon return.
186 *
187 * @param blocker the synchronization object responsible for this
188 * thread parking
189 * @since 1.6
190 */
191 public static void park(Object blocker) {
192 Thread t = Thread.currentThread();
193 setBlocker(t, blocker);
194 U.park(false, 0L);
195 setBlocker(t, null);
196 }
197
198 /**
199 * Disables the current thread for thread scheduling purposes, for up to
200 * the specified waiting time, unless the permit is available.
201 *
202 * <p>If the permit is available then it is consumed and the call
203 * returns immediately; otherwise the current thread becomes disabled
204 * for thread scheduling purposes and lies dormant until one of four
205 * things happens:
206 *
207 * <ul>
208 * <li>Some other thread invokes {@link #unpark unpark} with the
209 * current thread as the target; or
210 *
211 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
212 * the current thread; or
213 *
214 * <li>The specified waiting time elapses; or
215 *
216 * <li>The call spuriously (that is, for no reason) returns.
217 * </ul>
218 *
219 * <p>This method does <em>not</em> report which of these caused the
220 * method to return. Callers should re-check the conditions which caused
221 * the thread to park in the first place. Callers may also determine,
222 * for example, the interrupt status of the thread, or the elapsed time
223 * upon return.
224 *
225 * @param blocker the synchronization object responsible for this
226 * thread parking
227 * @param nanos the maximum number of nanoseconds to wait
228 * @since 1.6
229 */
230 public static void parkNanos(Object blocker, long nanos) {
231 if (nanos > 0) {
232 Thread t = Thread.currentThread();
233 setBlocker(t, blocker);
234 U.park(false, nanos);
235 setBlocker(t, null);
236 }
237 }
238
239 /**
240 * Disables the current thread for thread scheduling purposes, until
241 * the specified deadline, unless the permit is available.
242 *
243 * <p>If the permit is available then it is consumed and the call
244 * returns immediately; otherwise the current thread becomes disabled
245 * for thread scheduling purposes and lies dormant until one of four
246 * things happens:
247 *
248 * <ul>
249 * <li>Some other thread invokes {@link #unpark unpark} with the
250 * current thread as the target; or
251 *
252 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
253 * current thread; or
254 *
255 * <li>The specified deadline passes; or
256 *
257 * <li>The call spuriously (that is, for no reason) returns.
258 * </ul>
259 *
260 * <p>This method does <em>not</em> report which of these caused the
261 * method to return. Callers should re-check the conditions which caused
262 * the thread to park in the first place. Callers may also determine,
263 * for example, the interrupt status of the thread, or the current time
264 * upon return.
265 *
266 * @param blocker the synchronization object responsible for this
267 * thread parking
268 * @param deadline the absolute time, in milliseconds from the Epoch,
269 * to wait until
270 * @since 1.6
271 */
272 public static void parkUntil(Object blocker, long deadline) {
273 Thread t = Thread.currentThread();
274 setBlocker(t, blocker);
275 U.park(true, deadline);
276 setBlocker(t, null);
277 }
278
279 /**
280 * Returns the blocker object supplied to the most recent
281 * invocation of a park method that has not yet unblocked, or null
282 * if not blocked. The value returned is just a momentary
283 * snapshot -- the thread may have since unblocked or blocked on a
284 * different blocker object.
285 *
286 * @param t the thread
287 * @return the blocker
288 * @throws NullPointerException if argument is null
289 * @since 1.6
290 */
291 public static Object getBlocker(Thread t) {
292 if (t == null)
293 throw new NullPointerException();
294 return U.getObjectVolatile(t, PARKBLOCKER);
295 }
296
297 /**
298 * Disables the current thread for thread scheduling purposes unless the
299 * permit is available.
300 *
301 * <p>If the permit is available then it is consumed and the call
302 * returns immediately; otherwise the current thread becomes disabled
303 * for thread scheduling purposes and lies dormant until one of three
304 * things happens:
305 *
306 * <ul>
307 *
308 * <li>Some other thread invokes {@link #unpark unpark} with the
309 * current thread as the target; or
310 *
311 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
312 * the current thread; or
313 *
314 * <li>The call spuriously (that is, for no reason) returns.
315 * </ul>
316 *
317 * <p>This method does <em>not</em> report which of these caused the
318 * method to return. Callers should re-check the conditions which caused
319 * the thread to park in the first place. Callers may also determine,
320 * for example, the interrupt status of the thread upon return.
321 */
322 public static void park() {
323 U.park(false, 0L);
324 }
325
326 /**
327 * Disables the current thread for thread scheduling purposes, for up to
328 * the specified waiting time, unless the permit is available.
329 *
330 * <p>If the permit is available then it is consumed and the call
331 * returns immediately; otherwise the current thread becomes disabled
332 * for thread scheduling purposes and lies dormant until one of four
333 * things happens:
334 *
335 * <ul>
336 * <li>Some other thread invokes {@link #unpark unpark} with the
337 * current thread as the target; or
338 *
339 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
340 * the current thread; or
341 *
342 * <li>The specified waiting time elapses; or
343 *
344 * <li>The call spuriously (that is, for no reason) returns.
345 * </ul>
346 *
347 * <p>This method does <em>not</em> report which of these caused the
348 * method to return. Callers should re-check the conditions which caused
349 * the thread to park in the first place. Callers may also determine,
350 * for example, the interrupt status of the thread, or the elapsed time
351 * upon return.
352 *
353 * @param nanos the maximum number of nanoseconds to wait
354 */
355 public static void parkNanos(long nanos) {
356 if (nanos > 0)
357 U.park(false, nanos);
358 }
359
360 /**
361 * Disables the current thread for thread scheduling purposes, until
362 * the specified deadline, unless the permit is available.
363 *
364 * <p>If the permit is available then it is consumed and the call
365 * returns immediately; otherwise the current thread becomes disabled
366 * for thread scheduling purposes and lies dormant until one of four
367 * things happens:
368 *
369 * <ul>
370 * <li>Some other thread invokes {@link #unpark unpark} with the
371 * current thread as the target; or
372 *
373 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
374 * the current thread; or
375 *
376 * <li>The specified deadline passes; or
377 *
378 * <li>The call spuriously (that is, for no reason) returns.
379 * </ul>
380 *
381 * <p>This method does <em>not</em> report which of these caused the
382 * method to return. Callers should re-check the conditions which caused
383 * the thread to park in the first place. Callers may also determine,
384 * for example, the interrupt status of the thread, or the current time
385 * upon return.
386 *
387 * @param deadline the absolute time, in milliseconds from the Epoch,
388 * to wait until
389 */
390 public static void parkUntil(long deadline) {
391 U.park(true, deadline);
392 }
393
394 /**
395 * Returns the pseudo-randomly initialized or updated secondary seed.
396 * Copied from ThreadLocalRandom due to package access restrictions.
397 */
398 static final int nextSecondarySeed() {
399 int r;
400 Thread t = Thread.currentThread();
401 if ((r = U.getInt(t, SECONDARY)) != 0) {
402 r ^= r << 13; // xorshift
403 r ^= r >>> 17;
404 r ^= r << 5;
405 }
406 else if ((r = java.util.concurrent.ThreadLocalRandom.current().nextInt()) == 0)
407 r = 1; // avoid zero
408 U.putInt(t, SECONDARY, r);
409 return r;
410 }
411
412 /**
413 * Returns the thread id for the given thread. We must access
414 * this directly rather than via method Thread.getId() because
415 * getId() has been known to be overridden in ways that do not
416 * preserve unique mappings.
417 */
418 static final long getThreadId(Thread thread) {
419 return U.getLong(thread, TID);
420 }
421
422 // Hotspot implementation via intrinsics API
423 private static final Unsafe U = Unsafe.getUnsafe();
424 private static final long PARKBLOCKER = U.objectFieldOffset
425 (Thread.class, "parkBlocker");
426 private static final long SECONDARY = U.objectFieldOffset
427 (Thread.class, "threadLocalRandomSecondarySeed");
428 private static final long TID = U.objectFieldOffset
429 (Thread.class, "tid");
430
431 }
432