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