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.putReference(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 specified waiting time is zero or negative, the
 203      * method does nothing. Otherwise, if the permit is available then
 204      * it is consumed and the call returns immediately; otherwise the
 205      * current thread becomes disabled for thread scheduling purposes
 206      * and lies dormant until one of four things happens:
 207      *
 208      * <ul>
 209      * <li>Some other thread invokes {@link #unpark unpark} with the
 210      * current thread as the target; or
 211      *
 212      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 213      * the current thread; or
 214      *
 215      * <li>The specified waiting time elapses; or
 216      *
 217      * <li>The call spuriously (that is, for no reason) returns.
 218      * </ul>
 219      *
 220      * <p>This method does <em>not</em> report which of these caused the
 221      * method to return. Callers should re-check the conditions which caused
 222      * the thread to park in the first place. Callers may also determine,
 223      * for example, the interrupt status of the thread, or the elapsed time
 224      * upon return.
 225      *
 226      * @param blocker the synchronization object responsible for this
 227      *        thread parking
 228      * @param nanos the maximum number of nanoseconds to wait
 229      * @since 1.6
 230      */
 231     public static void parkNanos(Object blocker, long nanos) {
 232         if (nanos > 0) {
 233             Thread t = Thread.currentThread();
 234             setBlocker(t, blocker);
 235             U.park(false, nanos);
 236             setBlocker(t, null);
 237         }
 238     }
 239 
 240     /**
 241      * Disables the current thread for thread scheduling purposes, until
 242      * the specified deadline, unless the permit is available.
 243      *
 244      * <p>If the permit is available then it is consumed and the call
 245      * returns immediately; otherwise the current thread becomes disabled
 246      * for thread scheduling purposes and lies dormant until one of four
 247      * things happens:
 248      *
 249      * <ul>
 250      * <li>Some other thread invokes {@link #unpark unpark} with the
 251      * current thread as the target; or
 252      *
 253      * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
 254      * current thread; or
 255      *
 256      * <li>The specified deadline passes; or
 257      *
 258      * <li>The call spuriously (that is, for no reason) returns.
 259      * </ul>
 260      *
 261      * <p>This method does <em>not</em> report which of these caused the
 262      * method to return. Callers should re-check the conditions which caused
 263      * the thread to park in the first place. Callers may also determine,
 264      * for example, the interrupt status of the thread, or the current time
 265      * upon return.
 266      *
 267      * @param blocker the synchronization object responsible for this
 268      *        thread parking
 269      * @param deadline the absolute time, in milliseconds from the Epoch,
 270      *        to wait until
 271      * @since 1.6
 272      */
 273     public static void parkUntil(Object blocker, long deadline) {
 274         Thread t = Thread.currentThread();
 275         setBlocker(t, blocker);
 276         U.park(true, deadline);
 277         setBlocker(t, null);
 278     }
 279 
 280     /**
 281      * Returns the blocker object supplied to the most recent
 282      * invocation of a park method that has not yet unblocked, or null
 283      * if not blocked.  The value returned is just a momentary
 284      * snapshot -- the thread may have since unblocked or blocked on a
 285      * different blocker object.
 286      *
 287      * @param t the thread
 288      * @return the blocker
 289      * @throws NullPointerException if argument is null
 290      * @since 1.6
 291      */
 292     public static Object getBlocker(Thread t) {
 293         if (t == null)
 294             throw new NullPointerException();
 295         return U.getReferenceVolatile(t, PARKBLOCKER);
 296     }
 297 
 298     /**
 299      * Disables the current thread for thread scheduling purposes unless the
 300      * permit is available.
 301      *
 302      * <p>If the permit is available then it is consumed and the call
 303      * returns immediately; otherwise the current thread becomes disabled
 304      * for thread scheduling purposes and lies dormant until one of three
 305      * things happens:
 306      *
 307      * <ul>
 308      *
 309      * <li>Some other thread invokes {@link #unpark unpark} with the
 310      * current thread as the target; or
 311      *
 312      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 313      * the current thread; or
 314      *
 315      * <li>The call spuriously (that is, for no reason) returns.
 316      * </ul>
 317      *
 318      * <p>This method does <em>not</em> report which of these caused the
 319      * method to return. Callers should re-check the conditions which caused
 320      * the thread to park in the first place. Callers may also determine,
 321      * for example, the interrupt status of the thread upon return.
 322      */
 323     public static void park() {
 324         U.park(false, 0L);
 325     }
 326 
 327     /**
 328      * Disables the current thread for thread scheduling purposes, for up to
 329      * the specified waiting time, unless the permit is available.
 330      *
 331      * <p>If the specified waiting time is zero or negative, the
 332      * method does nothing. Otherwise, if the permit is available then
 333      * it is consumed and the call returns immediately; otherwise the
 334      * current thread becomes disabled for thread scheduling purposes
 335      * and lies dormant until one of four things happens:
 336      *
 337      * <ul>
 338      * <li>Some other thread invokes {@link #unpark unpark} with the
 339      * current thread as the target; or
 340      *
 341      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 342      * the current thread; or
 343      *
 344      * <li>The specified waiting time elapses; or
 345      *
 346      * <li>The call spuriously (that is, for no reason) returns.
 347      * </ul>
 348      *
 349      * <p>This method does <em>not</em> report which of these caused the
 350      * method to return. Callers should re-check the conditions which caused
 351      * the thread to park in the first place. Callers may also determine,
 352      * for example, the interrupt status of the thread, or the elapsed time
 353      * upon return.
 354      *
 355      * @param nanos the maximum number of nanoseconds to wait
 356      */
 357     public static void parkNanos(long nanos) {
 358         if (nanos > 0)
 359             U.park(false, nanos);
 360     }
 361 
 362     /**
 363      * Disables the current thread for thread scheduling purposes, until
 364      * the specified deadline, unless the permit is available.
 365      *
 366      * <p>If the permit is available then it is consumed and the call
 367      * returns immediately; otherwise the current thread becomes disabled
 368      * for thread scheduling purposes and lies dormant until one of four
 369      * things happens:
 370      *
 371      * <ul>
 372      * <li>Some other thread invokes {@link #unpark unpark} with the
 373      * current thread as the target; or
 374      *
 375      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 376      * the current thread; or
 377      *
 378      * <li>The specified deadline passes; or
 379      *
 380      * <li>The call spuriously (that is, for no reason) returns.
 381      * </ul>
 382      *
 383      * <p>This method does <em>not</em> report which of these caused the
 384      * method to return. Callers should re-check the conditions which caused
 385      * the thread to park in the first place. Callers may also determine,
 386      * for example, the interrupt status of the thread, or the current time
 387      * upon return.
 388      *
 389      * @param deadline the absolute time, in milliseconds from the Epoch,
 390      *        to wait until
 391      */
 392     public static void parkUntil(long deadline) {
 393         U.park(true, deadline);
 394     }
 395 
 396     /**
 397      * Returns the pseudo-randomly initialized or updated secondary seed.
 398      * Copied from ThreadLocalRandom due to package access restrictions.
 399      */
 400     static final int nextSecondarySeed() {
 401         int r;
 402         Thread t = Thread.currentThread();
 403         if ((r = U.getInt(t, SECONDARY)) != 0) {
 404             r ^= r << 13;   // xorshift
 405             r ^= r >>> 17;
 406             r ^= r << 5;
 407         }
 408         else if ((r = java.util.concurrent.ThreadLocalRandom.current().nextInt()) == 0)
 409             r = 1; // avoid zero
 410         U.putInt(t, SECONDARY, r);
 411         return r;
 412     }
 413 
 414     /**
 415      * Returns the thread id for the given thread.  We must access
 416      * this directly rather than via method Thread.getId() because
 417      * getId() has been known to be overridden in ways that do not
 418      * preserve unique mappings.
 419      */
 420     static final long getThreadId(Thread thread) {
 421         return U.getLong(thread, TID);
 422     }
 423 
 424     // Hotspot implementation via intrinsics API
 425     private static final Unsafe U = Unsafe.getUnsafe();
 426     private static final long PARKBLOCKER = U.objectFieldOffset
 427             (Thread.class, "parkBlocker");
 428     private static final long SECONDARY = U.objectFieldOffset
 429             (Thread.class, "threadLocalRandomSecondarySeed");
 430     private static final long TID = U.objectFieldOffset
 431             (Thread.class, "tid");
 432 
 433 }