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