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         U.putReferenceOpaque(t, PARKBLOCKER, arg);
 144     }
 145 
 146     /**
 147      * Sets the object to be returned by invocations of {@link
 148      * #getBlocker getBlocker} for the current thread. This method may
 149      * be used before invoking the no-argument version of {@link
 150      * LockSupport#park() park()} from non-public objects, allowing
 151      * more helpful diagnostics, or retaining compatibility with
 152      * previous implementations of blocking methods.  Previous values
 153      * of the blocker are not automatically restored after blocking.
 154      * To obtain the effects of {@code park(b}}, use {@code
 155      * setCurrentBlocker(b); park(); setCurrentBlocker(null);}
 156      *
 157      * @param blocker the blocker object
 158      * @since 14
 159      */
 160     public static void setCurrentBlocker(Object blocker) {
 161         U.putReferenceOpaque(Thread.currentThread(), PARKBLOCKER, blocker);
 162     }
 163 
 164     /**
 165      * Makes available the permit for the given thread, if it
 166      * was not already available.  If the thread was blocked on
 167      * {@code park} then it will unblock.  Otherwise, its next call
 168      * to {@code park} is guaranteed not to block. This operation
 169      * is not guaranteed to have any effect at all if the given
 170      * thread has not been started.
 171      *
 172      * @param thread the thread to unpark, or {@code null}, in which case
 173      *        this operation has no effect
 174      */
 175     public static void unpark(Thread thread) {
 176         if (thread != null)
 177             U.unpark(thread);
 178     }
 179 
 180     /**
 181      * Disables the current thread for thread scheduling purposes unless the
 182      * permit is available.
 183      *
 184      * <p>If the permit is available then it is consumed and the call returns
 185      * immediately; otherwise
 186      * the current thread becomes disabled for thread scheduling
 187      * purposes and lies dormant until one of three things happens:
 188      *
 189      * <ul>
 190      * <li>Some other thread invokes {@link #unpark unpark} with the
 191      * current thread as the target; or
 192      *
 193      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 194      * the current thread; or
 195      *
 196      * <li>The call spuriously (that is, for no reason) returns.
 197      * </ul>
 198      *
 199      * <p>This method does <em>not</em> report which of these caused the
 200      * method to return. Callers should re-check the conditions which caused
 201      * the thread to park in the first place. Callers may also determine,
 202      * for example, the interrupt status of the thread upon return.
 203      *
 204      * @param blocker the synchronization object responsible for this
 205      *        thread parking
 206      * @since 1.6
 207      */
 208     public static void park(Object blocker) {
 209         Thread t = Thread.currentThread();
 210         setBlocker(t, blocker);
 211         U.park(false, 0L);
 212         setBlocker(t, null);
 213     }
 214 
 215     /**
 216      * Disables the current thread for thread scheduling purposes, for up to
 217      * the specified waiting time, unless the permit is available.
 218      *
 219      * <p>If the specified waiting time is zero or negative, the
 220      * method does nothing. Otherwise, if the permit is available then
 221      * it is consumed and the call returns immediately; otherwise the
 222      * current thread becomes disabled for thread scheduling purposes
 223      * and lies dormant until one of four things happens:
 224      *
 225      * <ul>
 226      * <li>Some other thread invokes {@link #unpark unpark} with the
 227      * current thread as the target; or
 228      *
 229      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 230      * the current thread; or
 231      *
 232      * <li>The specified waiting time elapses; or
 233      *
 234      * <li>The call spuriously (that is, for no reason) returns.
 235      * </ul>
 236      *
 237      * <p>This method does <em>not</em> report which of these caused the
 238      * method to return. Callers should re-check the conditions which caused
 239      * the thread to park in the first place. Callers may also determine,
 240      * for example, the interrupt status of the thread, or the elapsed time
 241      * upon return.
 242      *
 243      * @param blocker the synchronization object responsible for this
 244      *        thread parking
 245      * @param nanos the maximum number of nanoseconds to wait
 246      * @since 1.6
 247      */
 248     public static void parkNanos(Object blocker, long nanos) {
 249         if (nanos > 0) {
 250             Thread t = Thread.currentThread();
 251             setBlocker(t, blocker);
 252             U.park(false, nanos);
 253             setBlocker(t, null);
 254         }
 255     }
 256 
 257     /**
 258      * Disables the current thread for thread scheduling purposes, until
 259      * the specified deadline, unless the permit is available.
 260      *
 261      * <p>If the permit is available then it is consumed and the call
 262      * returns immediately; otherwise the current thread becomes disabled
 263      * for thread scheduling purposes and lies dormant until one of four
 264      * things happens:
 265      *
 266      * <ul>
 267      * <li>Some other thread invokes {@link #unpark unpark} with the
 268      * current thread as the target; or
 269      *
 270      * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
 271      * current thread; or
 272      *
 273      * <li>The specified deadline passes; or
 274      *
 275      * <li>The call spuriously (that is, for no reason) returns.
 276      * </ul>
 277      *
 278      * <p>This method does <em>not</em> report which of these caused the
 279      * method to return. Callers should re-check the conditions which caused
 280      * the thread to park in the first place. Callers may also determine,
 281      * for example, the interrupt status of the thread, or the current time
 282      * upon return.
 283      *
 284      * @param blocker the synchronization object responsible for this
 285      *        thread parking
 286      * @param deadline the absolute time, in milliseconds from the Epoch,
 287      *        to wait until
 288      * @since 1.6
 289      */
 290     public static void parkUntil(Object blocker, long deadline) {
 291         Thread t = Thread.currentThread();
 292         setBlocker(t, blocker);
 293         U.park(true, deadline);
 294         setBlocker(t, null);
 295     }
 296 
 297     /**
 298      * Returns the blocker object supplied to the most recent
 299      * invocation of a park method that has not yet unblocked, or null
 300      * if not blocked.  The value returned is just a momentary
 301      * snapshot -- the thread may have since unblocked or blocked on a
 302      * different blocker object.
 303      *
 304      * @param t the thread
 305      * @return the blocker
 306      * @throws NullPointerException if argument is null
 307      * @since 1.6
 308      */
 309     public static Object getBlocker(Thread t) {
 310         if (t == null)
 311             throw new NullPointerException();
 312         return U.getReferenceOpaque(t, PARKBLOCKER);
 313     }
 314 
 315     /**
 316      * Disables the current thread for thread scheduling purposes unless the
 317      * permit is available.
 318      *
 319      * <p>If the permit is available then it is consumed and the call
 320      * returns immediately; otherwise the current thread becomes disabled
 321      * for thread scheduling purposes and lies dormant until one of three
 322      * things happens:
 323      *
 324      * <ul>
 325      *
 326      * <li>Some other thread invokes {@link #unpark unpark} with the
 327      * current thread as the target; or
 328      *
 329      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 330      * the current thread; or
 331      *
 332      * <li>The call spuriously (that is, for no reason) returns.
 333      * </ul>
 334      *
 335      * <p>This method does <em>not</em> report which of these caused the
 336      * method to return. Callers should re-check the conditions which caused
 337      * the thread to park in the first place. Callers may also determine,
 338      * for example, the interrupt status of the thread upon return.
 339      */
 340     public static void park() {
 341         U.park(false, 0L);
 342     }
 343 
 344     /**
 345      * Disables the current thread for thread scheduling purposes, for up to
 346      * the specified waiting time, unless the permit is available.
 347      *
 348      * <p>If the specified waiting time is zero or negative, the
 349      * method does nothing. Otherwise, if the permit is available then
 350      * it is consumed and the call returns immediately; otherwise the
 351      * current thread becomes disabled for thread scheduling purposes
 352      * and lies dormant until one of four things happens:
 353      *
 354      * <ul>
 355      * <li>Some other thread invokes {@link #unpark unpark} with the
 356      * current thread as the target; or
 357      *
 358      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 359      * the current thread; or
 360      *
 361      * <li>The specified waiting time elapses; or
 362      *
 363      * <li>The call spuriously (that is, for no reason) returns.
 364      * </ul>
 365      *
 366      * <p>This method does <em>not</em> report which of these caused the
 367      * method to return. Callers should re-check the conditions which caused
 368      * the thread to park in the first place. Callers may also determine,
 369      * for example, the interrupt status of the thread, or the elapsed time
 370      * upon return.
 371      *
 372      * @param nanos the maximum number of nanoseconds to wait
 373      */
 374     public static void parkNanos(long nanos) {
 375         if (nanos > 0)
 376             U.park(false, nanos);
 377     }
 378 
 379     /**
 380      * Disables the current thread for thread scheduling purposes, until
 381      * the specified deadline, unless the permit is available.
 382      *
 383      * <p>If the permit is available then it is consumed and the call
 384      * returns immediately; otherwise the current thread becomes disabled
 385      * for thread scheduling purposes and lies dormant until one of four
 386      * things happens:
 387      *
 388      * <ul>
 389      * <li>Some other thread invokes {@link #unpark unpark} with the
 390      * current thread as the target; or
 391      *
 392      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 393      * the current thread; or
 394      *
 395      * <li>The specified deadline passes; or
 396      *
 397      * <li>The call spuriously (that is, for no reason) returns.
 398      * </ul>
 399      *
 400      * <p>This method does <em>not</em> report which of these caused the
 401      * method to return. Callers should re-check the conditions which caused
 402      * the thread to park in the first place. Callers may also determine,
 403      * for example, the interrupt status of the thread, or the current time
 404      * upon return.
 405      *
 406      * @param deadline the absolute time, in milliseconds from the Epoch,
 407      *        to wait until
 408      */
 409     public static void parkUntil(long deadline) {
 410         U.park(true, deadline);
 411     }
 412 
 413     /**
 414      * Returns the thread id for the given thread.  We must access
 415      * this directly rather than via method Thread.getId() because
 416      * getId() has been known to be overridden in ways that do not
 417      * preserve unique mappings.
 418      */
 419     static final long getThreadId(Thread thread) {
 420         return U.getLong(thread, TID);
 421     }
 422 
 423     // Hotspot implementation via intrinsics API
 424     private static final Unsafe U = Unsafe.getUnsafe();
 425     private static final long PARKBLOCKER
 426         = U.objectFieldOffset(Thread.class, "parkBlocker");
 427     private static final long TID
 428         = U.objectFieldOffset(Thread.class, "tid");
 429 
 430 }