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 /**
  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()) { ... LockSupport.park(this); }}</pre>
  85  *
  86  * where neither {@code canProceed} nor any other actions prior to the
  87  * call to {@code park} entail locking or blocking.  Because only one
  88  * permit is associated with each thread, any intermediary uses of
  89  * {@code park} could interfere with its intended effects.
  90  *
  91  * <p><b>Sample Usage.</b> Here is a sketch of a first-in-first-out
  92  * non-reentrant lock class:
  93  * <pre> {@code
  94  * class FIFOMutex {
  95  *   private final AtomicBoolean locked = new AtomicBoolean(false);
  96  *   private final Queue<Thread> waiters
  97  *     = new ConcurrentLinkedQueue<>();
  98  *
  99  *   public void lock() {
 100  *     boolean wasInterrupted = false;
 101  *     Thread current = Thread.currentThread();
 102  *     waiters.add(current);
 103  *
 104  *     // Block while not first in queue or cannot acquire lock
 105  *     while (waiters.peek() != current ||
 106  *            !locked.compareAndSet(false, true)) {
 107  *       LockSupport.park(this);
 108  *       if (Thread.interrupted()) // ignore interrupts while waiting
 109  *         wasInterrupted = true;
 110  *     }
 111  *
 112  *     waiters.remove();
 113  *     if (wasInterrupted)          // reassert interrupt status on exit
 114  *       current.interrupt();
 115  *   }
 116  *
 117  *   public void unlock() {
 118  *     locked.set(false);
 119  *     LockSupport.unpark(waiters.peek());
 120  *   }
 121  * }}</pre>
 122  */
 123 public class LockSupport {
 124     private LockSupport() {} // Cannot be instantiated.
 125 
 126     private static void setBlocker(Thread t, Object arg) {
 127         // Even though volatile, hotspot doesn't need a write barrier here.
 128         U.putObject(t, PARKBLOCKER, arg);
 129     }
 130 
 131     /**
 132      * Makes available the permit for the given thread, if it
 133      * was not already available.  If the thread was blocked on
 134      * {@code park} then it will unblock.  Otherwise, its next call
 135      * to {@code park} is guaranteed not to block. This operation
 136      * is not guaranteed to have any effect at all if the given
 137      * thread has not been started.
 138      *
 139      * @param thread the thread to unpark, or {@code null}, in which case
 140      *        this operation has no effect
 141      */
 142     public static void unpark(Thread thread) {
 143         if (thread != null)
 144             U.unpark(thread);
 145     }
 146 
 147     /**
 148      * Disables the current thread for thread scheduling purposes unless the
 149      * permit is available.
 150      *
 151      * <p>If the permit is available then it is consumed and the call returns
 152      * immediately; otherwise
 153      * the current thread becomes disabled for thread scheduling
 154      * purposes and lies dormant until one of three things happens:
 155      *
 156      * <ul>
 157      * <li>Some other thread invokes {@link #unpark unpark} with the
 158      * current thread as the target; or
 159      *
 160      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 161      * the current thread; or
 162      *
 163      * <li>The call spuriously (that is, for no reason) returns.
 164      * </ul>
 165      *
 166      * <p>This method does <em>not</em> report which of these caused the
 167      * method to return. Callers should re-check the conditions which caused
 168      * the thread to park in the first place. Callers may also determine,
 169      * for example, the interrupt status of the thread upon return.
 170      *
 171      * @param blocker the synchronization object responsible for this
 172      *        thread parking
 173      * @since 1.6
 174      */
 175     public static void park(Object blocker) {
 176         Thread t = Thread.currentThread();
 177         setBlocker(t, blocker);
 178         U.park(false, 0L);
 179         setBlocker(t, null);
 180     }
 181 
 182     /**
 183      * Disables the current thread for thread scheduling purposes, for up to
 184      * the specified waiting time, unless the permit is available.
 185      *
 186      * <p>If the permit is available then it is consumed and the call
 187      * returns immediately; otherwise the current thread becomes disabled
 188      * for thread scheduling purposes and lies dormant until one of four
 189      * things happens:
 190      *
 191      * <ul>
 192      * <li>Some other thread invokes {@link #unpark unpark} with the
 193      * current thread as the target; or
 194      *
 195      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 196      * the current thread; or
 197      *
 198      * <li>The specified waiting time elapses; or
 199      *
 200      * <li>The call spuriously (that is, for no reason) returns.
 201      * </ul>
 202      *
 203      * <p>This method does <em>not</em> report which of these caused the
 204      * method to return. Callers should re-check the conditions which caused
 205      * the thread to park in the first place. Callers may also determine,
 206      * for example, the interrupt status of the thread, or the elapsed time
 207      * upon return.
 208      *
 209      * @param blocker the synchronization object responsible for this
 210      *        thread parking
 211      * @param nanos the maximum number of nanoseconds to wait
 212      * @since 1.6
 213      */
 214     public static void parkNanos(Object blocker, long nanos) {
 215         if (nanos > 0) {
 216             Thread t = Thread.currentThread();
 217             setBlocker(t, blocker);
 218             U.park(false, nanos);
 219             setBlocker(t, null);
 220         }
 221     }
 222 
 223     /**
 224      * Disables the current thread for thread scheduling purposes, until
 225      * the specified deadline, unless the permit is available.
 226      *
 227      * <p>If the permit is available then it is consumed and the call
 228      * returns immediately; otherwise the current thread becomes disabled
 229      * for thread scheduling purposes and lies dormant until one of four
 230      * things happens:
 231      *
 232      * <ul>
 233      * <li>Some other thread invokes {@link #unpark unpark} with the
 234      * current thread as the target; or
 235      *
 236      * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
 237      * current thread; or
 238      *
 239      * <li>The specified deadline passes; or
 240      *
 241      * <li>The call spuriously (that is, for no reason) returns.
 242      * </ul>
 243      *
 244      * <p>This method does <em>not</em> report which of these caused the
 245      * method to return. Callers should re-check the conditions which caused
 246      * the thread to park in the first place. Callers may also determine,
 247      * for example, the interrupt status of the thread, or the current time
 248      * upon return.
 249      *
 250      * @param blocker the synchronization object responsible for this
 251      *        thread parking
 252      * @param deadline the absolute time, in milliseconds from the Epoch,
 253      *        to wait until
 254      * @since 1.6
 255      */
 256     public static void parkUntil(Object blocker, long deadline) {
 257         Thread t = Thread.currentThread();
 258         setBlocker(t, blocker);
 259         U.park(true, deadline);
 260         setBlocker(t, null);
 261     }
 262 
 263     /**
 264      * Returns the blocker object supplied to the most recent
 265      * invocation of a park method that has not yet unblocked, or null
 266      * if not blocked.  The value returned is just a momentary
 267      * snapshot -- the thread may have since unblocked or blocked on a
 268      * different blocker object.
 269      *
 270      * @param t the thread
 271      * @return the blocker
 272      * @throws NullPointerException if argument is null
 273      * @since 1.6
 274      */
 275     public static Object getBlocker(Thread t) {
 276         if (t == null)
 277             throw new NullPointerException();
 278         return U.getObjectVolatile(t, PARKBLOCKER);
 279     }
 280 
 281     /**
 282      * Disables the current thread for thread scheduling purposes unless the
 283      * permit is available.
 284      *
 285      * <p>If the permit is available then it is consumed and the call
 286      * returns immediately; otherwise the current thread becomes disabled
 287      * for thread scheduling purposes and lies dormant until one of three
 288      * things happens:
 289      *
 290      * <ul>
 291      *
 292      * <li>Some other thread invokes {@link #unpark unpark} with the
 293      * current thread as the target; or
 294      *
 295      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 296      * the current thread; or
 297      *
 298      * <li>The call spuriously (that is, for no reason) returns.
 299      * </ul>
 300      *
 301      * <p>This method does <em>not</em> report which of these caused the
 302      * method to return. Callers should re-check the conditions which caused
 303      * the thread to park in the first place. Callers may also determine,
 304      * for example, the interrupt status of the thread upon return.
 305      */
 306     public static void park() {
 307         U.park(false, 0L);
 308     }
 309 
 310     /**
 311      * Disables the current thread for thread scheduling purposes, for up to
 312      * the specified waiting time, unless the permit is available.
 313      *
 314      * <p>If the permit is available then it is consumed and the call
 315      * returns immediately; otherwise the current thread becomes disabled
 316      * for thread scheduling purposes and lies dormant until one of four
 317      * things happens:
 318      *
 319      * <ul>
 320      * <li>Some other thread invokes {@link #unpark unpark} with the
 321      * current thread as the target; or
 322      *
 323      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 324      * the current thread; or
 325      *
 326      * <li>The specified waiting time elapses; or
 327      *
 328      * <li>The call spuriously (that is, for no reason) returns.
 329      * </ul>
 330      *
 331      * <p>This method does <em>not</em> report which of these caused the
 332      * method to return. Callers should re-check the conditions which caused
 333      * the thread to park in the first place. Callers may also determine,
 334      * for example, the interrupt status of the thread, or the elapsed time
 335      * upon return.
 336      *
 337      * @param nanos the maximum number of nanoseconds to wait
 338      */
 339     public static void parkNanos(long nanos) {
 340         if (nanos > 0)
 341             U.park(false, nanos);
 342     }
 343 
 344     /**
 345      * Disables the current thread for thread scheduling purposes, until
 346      * the specified deadline, unless the permit is available.
 347      *
 348      * <p>If the permit is available then it is consumed and the call
 349      * returns immediately; otherwise the current thread becomes disabled
 350      * for thread scheduling purposes and lies dormant until one of four
 351      * things happens:
 352      *
 353      * <ul>
 354      * <li>Some other thread invokes {@link #unpark unpark} with the
 355      * current thread as the target; or
 356      *
 357      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 358      * the current thread; or
 359      *
 360      * <li>The specified deadline passes; or
 361      *
 362      * <li>The call spuriously (that is, for no reason) returns.
 363      * </ul>
 364      *
 365      * <p>This method does <em>not</em> report which of these caused the
 366      * method to return. Callers should re-check the conditions which caused
 367      * the thread to park in the first place. Callers may also determine,
 368      * for example, the interrupt status of the thread, or the current time
 369      * upon return.
 370      *
 371      * @param deadline the absolute time, in milliseconds from the Epoch,
 372      *        to wait until
 373      */
 374     public static void parkUntil(long deadline) {
 375         U.park(true, deadline);
 376     }
 377 
 378     /**
 379      * Returns the pseudo-randomly initialized or updated secondary seed.
 380      * Copied from ThreadLocalRandom due to package access restrictions.
 381      */
 382     static final int nextSecondarySeed() {
 383         int r;
 384         Thread t = Thread.currentThread();
 385         if ((r = U.getInt(t, SECONDARY)) != 0) {
 386             r ^= r << 13;   // xorshift
 387             r ^= r >>> 17;
 388             r ^= r << 5;
 389         }
 390         else if ((r = java.util.concurrent.ThreadLocalRandom.current().nextInt()) == 0)
 391             r = 1; // avoid zero
 392         U.putInt(t, SECONDARY, r);
 393         return r;
 394     }
 395 
 396     // Hotspot implementation via intrinsics API
 397     private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
 398     private static final long PARKBLOCKER;
 399     private static final long SECONDARY;
 400     static {
 401         try {
 402             PARKBLOCKER = U.objectFieldOffset
 403                 (Thread.class.getDeclaredField("parkBlocker"));
 404             SECONDARY = U.objectFieldOffset
 405                 (Thread.class.getDeclaredField("threadLocalRandomSecondarySeed"));
 406         } catch (ReflectiveOperationException e) {
 407             throw new Error(e);
 408         }
 409     }
 410 
 411 }