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