001 /*
002 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
003 *
004 * This code is free software; you can redistribute it and/or modify it
005 * under the terms of the GNU General Public License version 2 only, as
006 * published by the Free Software Foundation. Sun designates this
007 * particular file as subject to the "Classpath" exception as provided
008 * by Sun in the LICENSE file that accompanied this code.
009 *
010 * This code is distributed in the hope that it will be useful, but WITHOUT
011 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
012 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
013 * version 2 for more details (a copy is included in the LICENSE file that
014 * accompanied this code).
015 *
016 * You should have received a copy of the GNU General Public License version
017 * 2 along with this work; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
019 *
020 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
021 * CA 95054 USA or visit www.sun.com if you need additional information or
022 * have any questions.
023 */
024
025 /*
026 * This file is available under and governed by the GNU General Public
027 * License version 2 only, as published by the Free Software Foundation.
028 * However, the following notice accompanied the original version of this
029 * file:
030 *
031 * Written by Doug Lea with assistance from members of JCP JSR-166
032 * Expert Group and released to the public domain, as explained at
033 * http://creativecommons.org/licenses/publicdomain
034 */
035
036 package java.util.concurrent.locks;
037
038 import java.util.concurrent.*;
039 import sun.misc.Unsafe;
040
041 /**
042 * Basic thread blocking primitives for creating locks and other
043 * synchronization classes.
044 *
045 * <p>This class associates, with each thread that uses it, a permit
046 * (in the sense of the {@link java.util.concurrent.Semaphore
047 * Semaphore} class). A call to {@code park} will return immediately
048 * if the permit is available, consuming it in the process; otherwise
049 * it <em>may</em> block. A call to {@code unpark} makes the permit
050 * available, if it was not already available. (Unlike with Semaphores
051 * though, permits do not accumulate. There is at most one.)
052 *
053 * <p>Methods {@code park} and {@code unpark} provide efficient
054 * means of blocking and unblocking threads that do not encounter the
055 * problems that cause the deprecated methods {@code Thread.suspend}
056 * and {@code Thread.resume} to be unusable for such purposes: Races
057 * between one thread invoking {@code park} and another thread trying
058 * to {@code unpark} it will preserve liveness, due to the
059 * permit. Additionally, {@code park} will return if the caller's
060 * thread was interrupted, and timeout versions are supported. The
061 * {@code park} method may also return at any other time, for "no
062 * reason", so in general must be invoked within a loop that rechecks
063 * conditions upon return. In this sense {@code park} serves as an
064 * optimization of a "busy wait" that does not waste as much time
065 * spinning, but must be paired with an {@code unpark} to be
066 * effective.
067 *
068 * <p>The three forms of {@code park} each also support a
069 * {@code blocker} object parameter. This object is recorded while
070 * the thread is blocked to permit monitoring and diagnostic tools to
071 * identify the reasons that threads are blocked. (Such tools may
072 * access blockers using method {@link #getBlocker}.) The use of these
073 * forms rather than the original forms without this parameter is
074 * strongly encouraged. The normal argument to supply as a
075 * {@code blocker} within a lock implementation is {@code this}.
076 *
077 * <p>These methods are designed to be used as tools for creating
078 * higher-level synchronization utilities, and are not in themselves
079 * useful for most concurrency control applications. The {@code park}
080 * method is designed for use only in constructions of the form:
081 * <pre>while (!canProceed()) { ... LockSupport.park(this); }</pre>
082 * where neither {@code canProceed} nor any other actions prior to the
083 * call to {@code park} entail locking or blocking. Because only one
084 * permit is associated with each thread, any intermediary uses of
085 * {@code park} could interfere with its intended effects.
086 *
087 * <p><b>Sample Usage.</b> Here is a sketch of a first-in-first-out
088 * non-reentrant lock class:
089 * <pre>{@code
090 * class FIFOMutex {
091 * private final AtomicBoolean locked = new AtomicBoolean(false);
092 * private final Queue<Thread> waiters
093 * = new ConcurrentLinkedQueue<Thread>();
094 *
095 * public void lock() {
096 * boolean wasInterrupted = false;
097 * Thread current = Thread.currentThread();
098 * waiters.add(current);
099 *
100 * // Block while not first in queue or cannot acquire lock
101 * while (waiters.peek() != current ||
102 * !locked.compareAndSet(false, true)) {
103 * LockSupport.park(this);
104 * if (Thread.interrupted()) // ignore interrupts while waiting
105 * wasInterrupted = true;
106 * }
107 *
108 * waiters.remove();
109 * if (wasInterrupted) // reassert interrupt status on exit
110 * current.interrupt();
111 * }
112 *
113 * public void unlock() {
114 * locked.set(false);
115 * LockSupport.unpark(waiters.peek());
116 * }
117 * }}</pre>
118 */
119
120 public class LockSupport {
121 private LockSupport() {
122 } // Cannot be instantiated.
123
124 // Hotspot implementation via intrinsics API
125 private static final Unsafe unsafe = Unsafe.getUnsafe();
126 private static final long parkBlockerOffset;
127
128 static {
129 try {
130 parkBlockerOffset = unsafe
131 .objectFieldOffset(java.lang.Thread.class
132 .getDeclaredField("parkBlocker"));
133 } catch (Exception ex) {
134 throw new Error(ex);
135 }
136 }
137
138 private static void setBlocker(Thread t, Object arg) {
139 // Even though volatile, hotspot doesn't need a write barrier here.
140 unsafe.putObject(t, parkBlockerOffset, arg);
141 }
142
143 /**
144 * Makes available the permit for the given thread, if it
145 * was not already available. If the thread was blocked on
146 * {@code park} then it will unblock. Otherwise, its next call
147 * to {@code park} is guaranteed not to block. This operation
148 * is not guaranteed to have any effect at all if the given
149 * thread has not been started.
150 *
151 * @param thread the thread to unpark, or {@code null}, in which case
152 * this operation has no effect
153 */
154 public static void unpark(Thread thread) {
155 if (thread != null)
156 unsafe.unpark(thread);
157 }
158
159 /**
160 * Disables the current thread for thread scheduling purposes unless the
161 * permit is available.
162 *
163 * <p>If the permit is available then it is consumed and the call returns
164 * immediately; otherwise
165 * the current thread becomes disabled for thread scheduling
166 * purposes and lies dormant until one of three things happens:
167 *
168 * <ul>
169 * <li>Some other thread invokes {@link #unpark unpark} with the
170 * current thread as the target; or
171 *
172 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
173 * the current thread; or
174 *
175 * <li>The call spuriously (that is, for no reason) returns.
176 * </ul>
177 *
178 * <p>This method does <em>not</em> report which of these caused the
179 * method to return. Callers should re-check the conditions which caused
180 * the thread to park in the first place. Callers may also determine,
181 * for example, the interrupt status of the thread upon return.
182 *
183 * @param blocker the synchronization object responsible for this
184 * thread parking
185 * @since 1.6
186 */
187 public static void park(Object blocker) {
188 Thread t = Thread.currentThread();
189 setBlocker(t, blocker);
190 unsafe.park(false, 0L);
191 setBlocker(t, null);
192 }
193
194 /**
195 * Disables the current thread for thread scheduling purposes, for up to
196 * the specified waiting time, unless the permit is available.
197 *
198 * <p>If the permit is available then it is consumed and the call
199 * returns immediately; otherwise the current thread becomes disabled
200 * for thread scheduling purposes and lies dormant until one of four
201 * things happens:
202 *
203 * <ul>
204 * <li>Some other thread invokes {@link #unpark unpark} with the
205 * current thread as the target; or
206 *
207 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the current
208 * thread; or
209 *
210 * <li>The specified waiting time elapses; or
211 *
212 * <li>The call spuriously (that is, for no reason) returns.
213 * </ul>
214 *
215 * <p>This method does <em>not</em> report which of these caused the
216 * method to return. Callers should re-check the conditions which caused
217 * the thread to park in the first place. Callers may also determine,
218 * for example, the interrupt status of the thread, or the elapsed time
219 * upon return.
220 *
221 * @param blocker the synchronization object responsible for this
222 * thread parking
223 * @param nanos the maximum number of nanoseconds to wait
224 * @since 1.6
225 */
226 public static void parkNanos(Object blocker, long nanos) {
227 if (nanos > 0) {
228 Thread t = Thread.currentThread();
229 setBlocker(t, blocker);
230 unsafe.park(false, nanos);
231 setBlocker(t, null);
232 }
233 }
234
235 /**
236 * Disables the current thread for thread scheduling purposes, until
237 * the specified deadline, unless the permit is available.
238 *
239 * <p>If the permit is available then it is consumed and the call
240 * returns immediately; otherwise the current thread becomes disabled
241 * for thread scheduling purposes and lies dormant until one of four
242 * things happens:
243 *
244 * <ul>
245 * <li>Some other thread invokes {@link #unpark unpark} with the
246 * current thread as the target; or
247 *
248 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
249 * current thread; or
250 *
251 * <li>The specified deadline passes; or
252 *
253 * <li>The call spuriously (that is, for no reason) returns.
254 * </ul>
255 *
256 * <p>This method does <em>not</em> report which of these caused the
257 * method to return. Callers should re-check the conditions which caused
258 * the thread to park in the first place. Callers may also determine,
259 * for example, the interrupt status of the thread, or the current time
260 * upon return.
261 *
262 * @param blocker the synchronization object responsible for this
263 * thread parking
264 * @param deadline the absolute time, in milliseconds from the Epoch,
265 * to wait until
266 * @since 1.6
267 */
268 public static void parkUntil(Object blocker, long deadline) {
269 Thread t = Thread.currentThread();
270 setBlocker(t, blocker);
271 unsafe.park(true, deadline);
272 setBlocker(t, null);
273 }
274
275 /**
276 * Returns the blocker object supplied to the most recent
277 * invocation of a park method that has not yet unblocked, or null
278 * if not blocked. The value returned is just a momentary
279 * snapshot -- the thread may have since unblocked or blocked on a
280 * different blocker object.
281 *
282 * @return the blocker
283 * @since 1.6
284 */
285 public static Object getBlocker(Thread t) {
286 return unsafe.getObjectVolatile(t, parkBlockerOffset);
287 }
288
289 /**
290 * Disables the current thread for thread scheduling purposes unless the
291 * permit is available.
292 *
293 * <p>If the permit is available then it is consumed and the call
294 * returns immediately; otherwise the current thread becomes disabled
295 * for thread scheduling purposes and lies dormant until one of three
296 * things happens:
297 *
298 * <ul>
299 *
300 * <li>Some other thread invokes {@link #unpark unpark} with the
301 * current thread as the target; or
302 *
303 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
304 * the current thread; or
305 *
306 * <li>The call spuriously (that is, for no reason) returns.
307 * </ul>
308 *
309 * <p>This method does <em>not</em> report which of these caused the
310 * method to return. Callers should re-check the conditions which caused
311 * the thread to park in the first place. Callers may also determine,
312 * for example, the interrupt status of the thread upon return.
313 */
314 public static void park() {
315 unsafe.park(false, 0L);
316 }
317
318 /**
319 * Disables the current thread for thread scheduling purposes, for up to
320 * the specified waiting time, unless the permit is available.
321 *
322 * <p>If the permit is available then it is consumed and the call
323 * returns immediately; otherwise the current thread becomes disabled
324 * for thread scheduling purposes and lies dormant until one of four
325 * things happens:
326 *
327 * <ul>
328 * <li>Some other thread invokes {@link #unpark unpark} with the
329 * current thread as the target; or
330 *
331 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
332 * the current thread; or
333 *
334 * <li>The specified waiting time elapses; or
335 *
336 * <li>The call spuriously (that is, for no reason) returns.
337 * </ul>
338 *
339 * <p>This method does <em>not</em> report which of these caused the
340 * method to return. Callers should re-check the conditions which caused
341 * the thread to park in the first place. Callers may also determine,
342 * for example, the interrupt status of the thread, or the elapsed time
343 * upon return.
344 *
345 * @param nanos the maximum number of nanoseconds to wait
346 */
347 public static void parkNanos(long nanos) {
348 if (nanos > 0)
349 unsafe.park(false, nanos);
350 }
351
352 /**
353 * Disables the current thread for thread scheduling purposes, until
354 * the specified deadline, unless the permit is available.
355 *
356 * <p>If the permit is available then it is consumed and the call
357 * returns immediately; otherwise the current thread becomes disabled
358 * for thread scheduling purposes and lies dormant until one of four
359 * things happens:
360 *
361 * <ul>
362 * <li>Some other thread invokes {@link #unpark unpark} with the
363 * current thread as the target; or
364 *
365 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
366 * the current thread; or
367 *
368 * <li>The specified deadline passes; or
369 *
370 * <li>The call spuriously (that is, for no reason) returns.
371 * </ul>
372 *
373 * <p>This method does <em>not</em> report which of these caused the
374 * method to return. Callers should re-check the conditions which caused
375 * the thread to park in the first place. Callers may also determine,
376 * for example, the interrupt status of the thread, or the current time
377 * upon return.
378 *
379 * @param deadline the absolute time, in milliseconds from the Epoch,
380 * to wait until
381 */
382 public static void parkUntil(long deadline) {
383 unsafe.park(true, deadline);
384 }
385 }
|