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