1/* 2 * Written by Doug Lea with assistance from members of JCP JSR-166 3 * Expert Group and released to the public domain, as explained at 4 * http://creativecommons.org/publicdomain/zero/1.0/ 5 */ 6 7package java.util.concurrent.locks; 8import sun.misc.Unsafe; 9 10 11/** 12 * Basic thread blocking primitives for creating locks and other 13 * synchronization classes. 14 * 15 * <p>This class associates, with each thread that uses it, a permit 16 * (in the sense of the {@link java.util.concurrent.Semaphore 17 * Semaphore} class). A call to {@code park} will return immediately 18 * if the permit is available, consuming it in the process; otherwise 19 * it <em>may</em> block. A call to {@code unpark} makes the permit 20 * available, if it was not already available. (Unlike with Semaphores 21 * though, permits do not accumulate. There is at most one.) 22 * 23 * <p>Methods {@code park} and {@code unpark} provide efficient 24 * means of blocking and unblocking threads that do not encounter the 25 * problems that cause the deprecated methods {@code Thread.suspend} 26 * and {@code Thread.resume} to be unusable for such purposes: Races 27 * between one thread invoking {@code park} and another thread trying 28 * to {@code unpark} it will preserve liveness, due to the 29 * permit. Additionally, {@code park} will return if the caller's 30 * thread was interrupted, and timeout versions are supported. The 31 * {@code park} method may also return at any other time, for "no 32 * reason", so in general must be invoked within a loop that rechecks 33 * conditions upon return. In this sense {@code park} serves as an 34 * optimization of a "busy wait" that does not waste as much time 35 * spinning, but must be paired with an {@code unpark} to be 36 * effective. 37 * 38 * <p>The three forms of {@code park} each also support a 39 * {@code blocker} object parameter. This object is recorded while 40 * the thread is blocked to permit monitoring and diagnostic tools to 41 * identify the reasons that threads are blocked. (Such tools may 42 * access blockers using method {@link #getBlocker}.) The use of these 43 * forms rather than the original forms without this parameter is 44 * strongly encouraged. The normal argument to supply as a 45 * {@code blocker} within a lock implementation is {@code this}. 46 * 47 * <p>These methods are designed to be used as tools for creating 48 * higher-level synchronization utilities, and are not in themselves 49 * useful for most concurrency control applications. The {@code park} 50 * method is designed for use only in constructions of the form: 51 * 52 * <pre> {@code 53 * while (!canProceed()) { ... LockSupport.park(this); }}</pre> 54 * 55 * where neither {@code canProceed} nor any other actions prior to the 56 * call to {@code park} entail locking or blocking. Because only one 57 * permit is associated with each thread, any intermediary uses of 58 * {@code park} could interfere with its intended effects. 59 * 60 * <p><b>Sample Usage.</b> Here is a sketch of a first-in-first-out 61 * non-reentrant lock class: 62 * <pre> {@code 63 * class FIFOMutex { 64 * private final AtomicBoolean locked = new AtomicBoolean(false); 65 * private final Queue<Thread> waiters 66 * = new ConcurrentLinkedQueue<Thread>(); 67 * 68 * public void lock() { 69 * boolean wasInterrupted = false; 70 * Thread current = Thread.currentThread(); 71 * waiters.add(current); 72 * 73 * // Block while not first in queue or cannot acquire lock 74 * while (waiters.peek() != current || 75 * !locked.compareAndSet(false, true)) { 76 * LockSupport.park(this); 77 * if (Thread.interrupted()) // ignore interrupts while waiting 78 * wasInterrupted = true; 79 * } 80 * 81 * waiters.remove(); 82 * if (wasInterrupted) // reassert interrupt status on exit 83 * current.interrupt(); 84 * } 85 * 86 * public void unlock() { 87 * locked.set(false); 88 * LockSupport.unpark(waiters.peek()); 89 * } 90 * }}</pre> 91 */ 92 93public class LockSupport { 94 private LockSupport() {} // Cannot be instantiated. 95 96 // Hotspot implementation via intrinsics API 97 private static final Unsafe unsafe = Unsafe.getUnsafe(); 98 private static final long parkBlockerOffset; 99 100 static { 101 try { 102 parkBlockerOffset = unsafe.objectFieldOffset 103 (java.lang.Thread.class.getDeclaredField("parkBlocker")); 104 } catch (Exception ex) { throw new Error(ex); } 105 } 106 107 private static void setBlocker(Thread t, Object arg) { 108 // Even though volatile, hotspot doesn't need a write barrier here. 109 unsafe.putObject(t, parkBlockerOffset, arg); 110 } 111 112 /** 113 * Makes available the permit for the given thread, if it 114 * was not already available. If the thread was blocked on 115 * {@code park} then it will unblock. Otherwise, its next call 116 * to {@code park} is guaranteed not to block. This operation 117 * is not guaranteed to have any effect at all if the given 118 * thread has not been started. 119 * 120 * @param thread the thread to unpark, or {@code null}, in which case 121 * this operation has no effect 122 */ 123 public static void unpark(Thread thread) { 124 if (thread != null) 125 unsafe.unpark(thread); 126 } 127 128 /** 129 * Disables the current thread for thread scheduling purposes unless the 130 * permit is available. 131 * 132 * <p>If the permit is available then it is consumed and the call returns 133 * immediately; otherwise 134 * the current thread becomes disabled for thread scheduling 135 * purposes and lies dormant until one of three things happens: 136 * 137 * <ul> 138 * <li>Some other thread invokes {@link #unpark unpark} with the 139 * current thread as the target; or 140 * 141 * <li>Some other thread {@linkplain Thread#interrupt interrupts} 142 * the current thread; or 143 * 144 * <li>The call spuriously (that is, for no reason) returns. 145 * </ul> 146 * 147 * <p>This method does <em>not</em> report which of these caused the 148 * method to return. Callers should re-check the conditions which caused 149 * the thread to park in the first place. Callers may also determine, 150 * for example, the interrupt status of the thread upon return. 151 * 152 * @param blocker the synchronization object responsible for this 153 * thread parking 154 * @since 1.6 155 */ 156 public static void park(Object blocker) { 157 Thread t = Thread.currentThread(); 158 setBlocker(t, blocker); 159 unsafe.park(false, 0L); 160 setBlocker(t, null); 161 } 162 163 /** 164 * Disables the current thread for thread scheduling purposes, for up to 165 * the specified waiting time, unless the permit is available. 166 * 167 * <p>If the permit is available then it is consumed and the call 168 * returns immediately; otherwise the current thread becomes disabled 169 * for thread scheduling purposes and lies dormant until one of four 170 * 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 specified waiting time elapses; or 180 * 181 * <li>The call spuriously (that is, for no reason) returns. 182 * </ul> 183 * 184 * <p>This method does <em>not</em> report which of these caused the 185 * method to return. Callers should re-check the conditions which caused 186 * the thread to park in the first place. Callers may also determine, 187 * for example, the interrupt status of the thread, or the elapsed time 188 * upon return. 189 * 190 * @param blocker the synchronization object responsible for this 191 * thread parking 192 * @param nanos the maximum number of nanoseconds to wait 193 * @since 1.6 194 */ 195 public static void parkNanos(Object blocker, long nanos) { 196 if (nanos > 0) { 197 Thread t = Thread.currentThread(); 198 setBlocker(t, blocker); 199 unsafe.park(false, nanos); 200 setBlocker(t, null); 201 } 202 } 203 204 /** 205 * Disables the current thread for thread scheduling purposes, until 206 * the specified deadline, unless the permit is available. 207 * 208 * <p>If the permit is available then it is consumed and the call 209 * returns immediately; otherwise the current thread becomes disabled 210 * for thread scheduling purposes and lies dormant until one of four 211 * things happens: 212 * 213 * <ul> 214 * <li>Some other thread invokes {@link #unpark unpark} with the 215 * current thread as the target; or 216 * 217 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the 218 * current thread; or 219 * 220 * <li>The specified deadline passes; or 221 * 222 * <li>The call spuriously (that is, for no reason) returns. 223 * </ul> 224 * 225 * <p>This method does <em>not</em> report which of these caused the 226 * method to return. Callers should re-check the conditions which caused 227 * the thread to park in the first place. Callers may also determine, 228 * for example, the interrupt status of the thread, or the current time 229 * upon return. 230 * 231 * @param blocker the synchronization object responsible for this 232 * thread parking 233 * @param deadline the absolute time, in milliseconds from the Epoch, 234 * to wait until 235 * @since 1.6 236 */ 237 public static void parkUntil(Object blocker, long deadline) { 238 Thread t = Thread.currentThread(); 239 setBlocker(t, blocker); 240 unsafe.park(true, deadline); 241 setBlocker(t, null); 242 } 243 244 /** 245 * Returns the blocker object supplied to the most recent 246 * invocation of a park method that has not yet unblocked, or null 247 * if not blocked. The value returned is just a momentary 248 * snapshot -- the thread may have since unblocked or blocked on a 249 * different blocker object. 250 * 251 * @param t the thread 252 * @return the blocker 253 * @throws NullPointerException if argument is null 254 * @since 1.6 255 */ 256 public static Object getBlocker(Thread t) { 257 if (t == null) 258 throw new NullPointerException(); 259 return unsafe.getObjectVolatile(t, parkBlockerOffset); 260 } 261 262 /** 263 * Disables the current thread for thread scheduling purposes unless the 264 * permit is available. 265 * 266 * <p>If the permit is available then it is consumed and the call 267 * returns immediately; otherwise the current thread becomes disabled 268 * for thread scheduling purposes and lies dormant until one of three 269 * things happens: 270 * 271 * <ul> 272 * 273 * <li>Some other thread invokes {@link #unpark unpark} with the 274 * current thread as the target; or 275 * 276 * <li>Some other thread {@linkplain Thread#interrupt interrupts} 277 * the current thread; or 278 * 279 * <li>The call spuriously (that is, for no reason) returns. 280 * </ul> 281 * 282 * <p>This method does <em>not</em> report which of these caused the 283 * method to return. Callers should re-check the conditions which caused 284 * the thread to park in the first place. Callers may also determine, 285 * for example, the interrupt status of the thread upon return. 286 */ 287 public static void park() { 288 unsafe.park(false, 0L); 289 } 290 291 /** 292 * Disables the current thread for thread scheduling purposes, for up to 293 * the specified waiting time, unless the permit is available. 294 * 295 * <p>If the permit is available then it is consumed and the call 296 * returns immediately; otherwise the current thread becomes disabled 297 * for thread scheduling purposes and lies dormant until one of four 298 * things happens: 299 * 300 * <ul> 301 * <li>Some other thread invokes {@link #unpark unpark} with the 302 * current thread as the target; or 303 * 304 * <li>Some other thread {@linkplain Thread#interrupt interrupts} 305 * the current thread; or 306 * 307 * <li>The specified waiting time elapses; or 308 * 309 * <li>The call spuriously (that is, for no reason) returns. 310 * </ul> 311 * 312 * <p>This method does <em>not</em> report which of these caused the 313 * method to return. Callers should re-check the conditions which caused 314 * the thread to park in the first place. Callers may also determine, 315 * for example, the interrupt status of the thread, or the elapsed time 316 * upon return. 317 * 318 * @param nanos the maximum number of nanoseconds to wait 319 */ 320 public static void parkNanos(long nanos) { 321 if (nanos > 0) 322 unsafe.park(false, nanos); 323 } 324 325 /** 326 * Disables the current thread for thread scheduling purposes, until 327 * the specified deadline, unless the permit is available. 328 * 329 * <p>If the permit is available then it is consumed and the call 330 * returns immediately; otherwise the current thread becomes disabled 331 * for thread scheduling purposes and lies dormant until one of four 332 * things happens: 333 * 334 * <ul> 335 * <li>Some other thread invokes {@link #unpark unpark} with the 336 * current thread as the target; or 337 * 338 * <li>Some other thread {@linkplain Thread#interrupt interrupts} 339 * the current thread; or 340 * 341 * <li>The specified deadline passes; or 342 * 343 * <li>The call spuriously (that is, for no reason) returns. 344 * </ul> 345 * 346 * <p>This method does <em>not</em> report which of these caused the 347 * method to return. Callers should re-check the conditions which caused 348 * the thread to park in the first place. Callers may also determine, 349 * for example, the interrupt status of the thread, or the current time 350 * upon return. 351 * 352 * @param deadline the absolute time, in milliseconds from the Epoch, 353 * to wait until 354 */ 355 public static void parkUntil(long deadline) { 356 unsafe.park(true, deadline); 357 } 358} 359