Showing the changes to java/pkg/java/util/concurrent/locks (34 of 18352 files). Show all
Unified · Split
Binary file not shown.
| @@ -0,0 +1,86 @@ | ||
| 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 | + * A synchronizer that may be exclusively owned by a thread. This | |
| 40 | + * class provides a basis for creating locks and related synchronizers | |
| 41 | + * that may entail a notion of ownership. The | |
| 42 | + * <tt>AbstractOwnableSynchronizer</tt> class itself does not manage or | |
| 43 | + * use this information. However, subclasses and tools may use | |
| 44 | + * appropriately maintained values to help control and monitor access | |
| 45 | + * and provide diagnostics. | |
| 46 | + * | |
| 47 | + * @since 1.6 | |
| 48 | + * @author Doug Lea | |
| 49 | + */ | |
| 50 | +public abstract class AbstractOwnableSynchronizer | |
| 51 | + implements java.io.Serializable { | |
| 52 | + | |
| 53 | + /** Use serial ID even though all fields transient. */ | |
| 54 | + private static final long serialVersionUID = 3737899427754241961L; | |
| 55 | + | |
| 56 | + /** | |
| 57 | + * Empty constructor for use by subclasses. | |
| 58 | + */ | |
| 59 | + protected AbstractOwnableSynchronizer() { } | |
| 60 | + | |
| 61 | + /** | |
| 62 | + * The current owner of exclusive mode synchronization. | |
| 63 | + */ | |
| 64 | + private transient Thread exclusiveOwnerThread; | |
| 65 | + | |
| 66 | + /** | |
| 67 | + * Sets the thread that currently owns exclusive access. A | |
| 68 | + * <tt>null</tt> argument indicates that no thread owns access. | |
| 69 | + * This method does not otherwise impose any synchronization or | |
| 70 | + * <tt>volatile</tt> field accesses. | |
| 71 | + */ | |
| 72 | + protected final void setExclusiveOwnerThread(Thread t) { | |
| 73 | + exclusiveOwnerThread = t; | |
| 74 | + } | |
| 75 | + | |
| 76 | + /** | |
| 77 | + * Returns the thread last set by | |
| 78 | + * <tt>setExclusiveOwnerThread</tt>, or <tt>null</tt> if never | |
| 79 | + * set. This method does not otherwise impose any synchronization | |
| 80 | + * or <tt>volatile</tt> field accesses. | |
| 81 | + * @return the owner thread | |
| 82 | + */ | |
| 83 | + protected final Thread getExclusiveOwnerThread() { | |
| 84 | + return exclusiveOwnerThread; | |
| 85 | + } | |
| 86 | +} | |
Binary file not shown.
Binary file not shown.
Binary file not shown.
| @@ -0,0 +1,2109 @@ | ||
| 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 | +import java.util.*; | |
| 38 | +import java.util.concurrent.*; | |
| 39 | +import java.util.concurrent.atomic.*; | |
| 40 | +import sun.misc.Unsafe; | |
| 41 | + | |
| 42 | +/** | |
| 43 | + * A version of {@link AbstractQueuedSynchronizer} in | |
| 44 | + * which synchronization state is maintained as a <tt>long</tt>. | |
| 45 | + * This class has exactly the same structure, properties, and methods | |
| 46 | + * as <tt>AbstractQueuedSynchronizer</tt> with the exception | |
| 47 | + * that all state-related parameters and results are defined | |
| 48 | + * as <tt>long</tt> rather than <tt>int</tt>. This class | |
| 49 | + * may be useful when creating synchronizers such as | |
| 50 | + * multilevel locks and barriers that require | |
| 51 | + * 64 bits of state. | |
| 52 | + * | |
| 53 | + * <p>See {@link AbstractQueuedSynchronizer} for usage | |
| 54 | + * notes and examples. | |
| 55 | + * | |
| 56 | + * @since 1.6 | |
| 57 | + * @author Doug Lea | |
| 58 | + */ | |
| 59 | +public abstract class AbstractQueuedLongSynchronizer | |
| 60 | + extends AbstractOwnableSynchronizer | |
| 61 | + implements java.io.Serializable { | |
| 62 | + | |
| 63 | + private static final long serialVersionUID = 7373984972572414692L; | |
| 64 | + | |
| 65 | + /* | |
| 66 | + To keep sources in sync, the remainder of this source file is | |
| 67 | + exactly cloned from AbstractQueuedSynchronizer, replacing class | |
| 68 | + name and changing ints related with sync state to longs. Please | |
| 69 | + keep it that way. | |
| 70 | + */ | |
| 71 | + | |
| 72 | + /** | |
| 73 | + * Creates a new <tt>AbstractQueuedLongSynchronizer</tt> instance | |
| 74 | + * with initial synchronization state of zero. | |
| 75 | + */ | |
| 76 | + protected AbstractQueuedLongSynchronizer() { } | |
| 77 | + | |
| 78 | + /** | |
| 79 | + * Wait queue node class. | |
| 80 | + * | |
| 81 | + * <p>The wait queue is a variant of a "CLH" (Craig, Landin, and | |
| 82 | + * Hagersten) lock queue. CLH locks are normally used for | |
| 83 | + * spinlocks. We instead use them for blocking synchronizers, but | |
| 84 | + * use the same basic tactic of holding some of the control | |
| 85 | + * information about a thread in the predecessor of its node. A | |
| 86 | + * "status" field in each node keeps track of whether a thread | |
| 87 | + * should block. A node is signalled when its predecessor | |
| 88 | + * releases. Each node of the queue otherwise serves as a | |
| 89 | + * specific-notification-style monitor holding a single waiting | |
| 90 | + * thread. The status field does NOT control whether threads are | |
| 91 | + * granted locks etc though. A thread may try to acquire if it is | |
| 92 | + * first in the queue. But being first does not guarantee success; | |
| 93 | + * it only gives the right to contend. So the currently released | |
| 94 | + * contender thread may need to rewait. | |
| 95 | + * | |
| 96 | + * <p>To enqueue into a CLH lock, you atomically splice it in as new | |
| 97 | + * tail. To dequeue, you just set the head field. | |
| 98 | + * <pre> | |
| 99 | + * +------+ prev +-----+ +-----+ | |
| 100 | + * head | | <---- | | <---- | | tail | |
| 101 | + * +------+ +-----+ +-----+ | |
| 102 | + * </pre> | |
| 103 | + * | |
| 104 | + * <p>Insertion into a CLH queue requires only a single atomic | |
| 105 | + * operation on "tail", so there is a simple atomic point of | |
| 106 | + * demarcation from unqueued to queued. Similarly, dequeing | |
| 107 | + * involves only updating the "head". However, it takes a bit | |
| 108 | + * more work for nodes to determine who their successors are, | |
| 109 | + * in part to deal with possible cancellation due to timeouts | |
| 110 | + * and interrupts. | |
| 111 | + * | |
| 112 | + * <p>The "prev" links (not used in original CLH locks), are mainly | |
| 113 | + * needed to handle cancellation. If a node is cancelled, its | |
| 114 | + * successor is (normally) relinked to a non-cancelled | |
| 115 | + * predecessor. For explanation of similar mechanics in the case | |
| 116 | + * of spin locks, see the papers by Scott and Scherer at | |
| 117 | + * http://www.cs.rochester.edu/u/scott/synchronization/ | |
| 118 | + * | |
| 119 | + * <p>We also use "next" links to implement blocking mechanics. | |
| 120 | + * The thread id for each node is kept in its own node, so a | |
| 121 | + * predecessor signals the next node to wake up by traversing | |
| 122 | + * next link to determine which thread it is. Determination of | |
| 123 | + * successor must avoid races with newly queued nodes to set | |
| 124 | + * the "next" fields of their predecessors. This is solved | |
| 125 | + * when necessary by checking backwards from the atomically | |
| 126 | + * updated "tail" when a node's successor appears to be null. | |
| 127 | + * (Or, said differently, the next-links are an optimization | |
| 128 | + * so that we don't usually need a backward scan.) | |
| 129 | + * | |
| 130 | + * <p>Cancellation introduces some conservatism to the basic | |
| 131 | + * algorithms. Since we must poll for cancellation of other | |
| 132 | + * nodes, we can miss noticing whether a cancelled node is | |
| 133 | + * ahead or behind us. This is dealt with by always unparking | |
| 134 | + * successors upon cancellation, allowing them to stabilize on | |
| 135 | + * a new predecessor, unless we can identify an uncancelled | |
| 136 | + * predecessor who will carry this responsibility. | |
| 137 | + * | |
| 138 | + * <p>CLH queues need a dummy header node to get started. But | |
| 139 | + * we don't create them on construction, because it would be wasted | |
| 140 | + * effort if there is never contention. Instead, the node | |
| 141 | + * is constructed and head and tail pointers are set upon first | |
| 142 | + * contention. | |
| 143 | + * | |
| 144 | + * <p>Threads waiting on Conditions use the same nodes, but | |
| 145 | + * use an additional link. Conditions only need to link nodes | |
| 146 | + * in simple (non-concurrent) linked queues because they are | |
| 147 | + * only accessed when exclusively held. Upon await, a node is | |
| 148 | + * inserted into a condition queue. Upon signal, the node is | |
| 149 | + * transferred to the main queue. A special value of status | |
| 150 | + * field is used to mark which queue a node is on. | |
| 151 | + * | |
| 152 | + * <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill | |
| 153 | + * Scherer and Michael Scott, along with members of JSR-166 | |
| 154 | + * expert group, for helpful ideas, discussions, and critiques | |
| 155 | + * on the design of this class. | |
| 156 | + */ | |
| 157 | + static final class Node { | |
| 158 | + /** Marker to indicate a node is waiting in shared mode */ | |
| 159 | + static final Node SHARED = new Node(); | |
| 160 | + /** Marker to indicate a node is waiting in exclusive mode */ | |
| 161 | + static final Node EXCLUSIVE = null; | |
| 162 | + | |
| 163 | + /** waitStatus value to indicate thread has cancelled */ | |
| 164 | + static final int CANCELLED = 1; | |
| 165 | + /** waitStatus value to indicate successor's thread needs unparking */ | |
| 166 | + static final int SIGNAL = -1; | |
| 167 | + /** waitStatus value to indicate thread is waiting on condition */ | |
| 168 | + static final int CONDITION = -2; | |
| 169 | + /** | |
| 170 | + * waitStatus value to indicate the next acquireShared should | |
| 171 | + * unconditionally propagate | |
| 172 | + */ | |
| 173 | + static final int PROPAGATE = -3; | |
| 174 | + | |
| 175 | + /** | |
| 176 | + * Status field, taking on only the values: | |
| 177 | + * SIGNAL: The successor of this node is (or will soon be) | |
| 178 | + * blocked (via park), so the current node must | |
| 179 | + * unpark its successor when it releases or | |
| 180 | + * cancels. To avoid races, acquire methods must | |
| 181 | + * first indicate they need a signal, | |
| 182 | + * then retry the atomic acquire, and then, | |
| 183 | + * on failure, block. | |
| 184 | + * CANCELLED: This node is cancelled due to timeout or interrupt. | |
| 185 | + * Nodes never leave this state. In particular, | |
| 186 | + * a thread with cancelled node never again blocks. | |
| 187 | + * CONDITION: This node is currently on a condition queue. | |
| 188 | + * It will not be used as a sync queue node | |
| 189 | + * until transferred, at which time the status | |
| 190 | + * will be set to 0. (Use of this value here has | |
| 191 | + * nothing to do with the other uses of the | |
| 192 | + * field, but simplifies mechanics.) | |
| 193 | + * PROPAGATE: A releaseShared should be propagated to other | |
| 194 | + * nodes. This is set (for head node only) in | |
| 195 | + * doReleaseShared to ensure propagation | |
| 196 | + * continues, even if other operations have | |
| 197 | + * since intervened. | |
| 198 | + * 0: None of the above | |
| 199 | + * | |
| 200 | + * The values are arranged numerically to simplify use. | |
| 201 | + * Non-negative values mean that a node doesn't need to | |
| 202 | + * signal. So, most code doesn't need to check for particular | |
| 203 | + * values, just for sign. | |
| 204 | + * | |
| 205 | + * The field is initialized to 0 for normal sync nodes, and | |
| 206 | + * CONDITION for condition nodes. It is modified using CAS | |
| 207 | + * (or when possible, unconditional volatile writes). | |
| 208 | + */ | |
| 209 | + volatile int waitStatus; | |
| 210 | + | |
| 211 | + /** | |
| 212 | + * Link to predecessor node that current node/thread relies on | |
| 213 | + * for checking waitStatus. Assigned during enqueing, and nulled | |
| 214 | + * out (for sake of GC) only upon dequeuing. Also, upon | |
| 215 | + * cancellation of a predecessor, we short-circuit while | |
| 216 | + * finding a non-cancelled one, which will always exist | |
| 217 | + * because the head node is never cancelled: A node becomes | |
| 218 | + * head only as a result of successful acquire. A | |
| 219 | + * cancelled thread never succeeds in acquiring, and a thread only | |
| 220 | + * cancels itself, not any other node. | |
| 221 | + */ | |
| 222 | + volatile Node prev; | |
| 223 | + | |
| 224 | + /** | |
| 225 | + * Link to the successor node that the current node/thread | |
| 226 | + * unparks upon release. Assigned during enqueuing, adjusted | |
| 227 | + * when bypassing cancelled predecessors, and nulled out (for | |
| 228 | + * sake of GC) when dequeued. The enq operation does not | |
| 229 | + * assign next field of a predecessor until after attachment, | |
| 230 | + * so seeing a null next field does not necessarily mean that | |
| 231 | + * node is at end of queue. However, if a next field appears | |
| 232 | + * to be null, we can scan prev's from the tail to | |
| 233 | + * double-check. The next field of cancelled nodes is set to | |
| 234 | + * point to the node itself instead of null, to make life | |
| 235 | + * easier for isOnSyncQueue. | |
| 236 | + */ | |
| 237 | + volatile Node next; | |
| 238 | + | |
| 239 | + /** | |
| 240 | + * The thread that enqueued this node. Initialized on | |
| 241 | + * construction and nulled out after use. | |
| 242 | + */ | |
| 243 | + volatile Thread thread; | |
| 244 | + | |
| 245 | + /** | |
| 246 | + * Link to next node waiting on condition, or the special | |
| 247 | + * value SHARED. Because condition queues are accessed only | |
| 248 | + * when holding in exclusive mode, we just need a simple | |
| 249 | + * linked queue to hold nodes while they are waiting on | |
| 250 | + * conditions. They are then transferred to the queue to | |
| 251 | + * re-acquire. And because conditions can only be exclusive, | |
| 252 | + * we save a field by using special value to indicate shared | |
| 253 | + * mode. | |
| 254 | + */ | |
| 255 | + Node nextWaiter; | |
| 256 | + | |
| 257 | + /** | |
| 258 | + * Returns true if node is waiting in shared mode | |
| 259 | + */ | |
| 260 | + final boolean isShared() { | |
| 261 | + return nextWaiter == SHARED; | |
| 262 | + } | |
| 263 | + | |
| 264 | + /** | |
| 265 | + * Returns previous node, or throws NullPointerException if null. | |
| 266 | + * Use when predecessor cannot be null. The null check could | |
| 267 | + * be elided, but is present to help the VM. | |
| 268 | + * | |
| 269 | + * @return the predecessor of this node | |
| 270 | + */ | |
| 271 | + final Node predecessor() throws NullPointerException { | |
| 272 | + Node p = prev; | |
| 273 | + if (p == null) | |
| 274 | + throw new NullPointerException(); | |
| 275 | + else | |
| 276 | + return p; | |
| 277 | + } | |
| 278 | + | |
| 279 | + Node() { // Used to establish initial head or SHARED marker | |
| 280 | + } | |
| 281 | + | |
| 282 | + Node(Thread thread, Node mode) { // Used by addWaiter | |
| 283 | + this.nextWaiter = mode; | |
| 284 | + this.thread = thread; | |
| 285 | + } | |
| 286 | + | |
| 287 | + Node(Thread thread, int waitStatus) { // Used by Condition | |
| 288 | + this.waitStatus = waitStatus; | |
| 289 | + this.thread = thread; | |
| 290 | + } | |
| 291 | + } | |
| 292 | + | |
| 293 | + /** | |
| 294 | + * Head of the wait queue, lazily initialized. Except for | |
| 295 | + * initialization, it is modified only via method setHead. Note: | |
| 296 | + * If head exists, its waitStatus is guaranteed not to be | |
| 297 | + * CANCELLED. | |
| 298 | + */ | |
| 299 | + private transient volatile Node head; | |
| 300 | + | |
| 301 | + /** | |
| 302 | + * Tail of the wait queue, lazily initialized. Modified only via | |
| 303 | + * method enq to add new wait node. | |
| 304 | + */ | |
| 305 | + private transient volatile Node tail; | |
| 306 | + | |
| 307 | + /** | |
| 308 | + * The synchronization state. | |
| 309 | + */ | |
| 310 | + private volatile long state; | |
| 311 | + | |
| 312 | + /** | |
| 313 | + * Returns the current value of synchronization state. | |
| 314 | + * This operation has memory semantics of a <tt>volatile</tt> read. | |
| 315 | + * @return current state value | |
| 316 | + */ | |
| 317 | + protected final long getState() { | |
| 318 | + return state; | |
| 319 | + } | |
| 320 | + | |
| 321 | + /** | |
| 322 | + * Sets the value of synchronization state. | |
| 323 | + * This operation has memory semantics of a <tt>volatile</tt> write. | |
| 324 | + * @param newState the new state value | |
| 325 | + */ | |
| 326 | + protected final void setState(long newState) { | |
| 327 | + state = newState; | |
| 328 | + } | |
| 329 | + | |
| 330 | + /** | |
| 331 | + * Atomically sets synchronization state to the given updated | |
| 332 | + * value if the current state value equals the expected value. | |
| 333 | + * This operation has memory semantics of a <tt>volatile</tt> read | |
| 334 | + * and write. | |
| 335 | + * | |
| 336 | + * @param expect the expected value | |
| 337 | + * @param update the new value | |
| 338 | + * @return true if successful. False return indicates that the actual | |
| 339 | + * value was not equal to the expected value. | |
| 340 | + */ | |
| 341 | + protected final boolean compareAndSetState(long expect, long update) { | |
| 342 | + // See below for intrinsics setup to support this | |
| 343 | + return unsafe.compareAndSwapLong(this, stateOffset, expect, update); | |
| 344 | + } | |
| 345 | + | |
| 346 | + // Queuing utilities | |
| 347 | + | |
| 348 | + /** | |
| 349 | + * The number of nanoseconds for which it is faster to spin | |
| 350 | + * rather than to use timed park. A rough estimate suffices | |
| 351 | + * to improve responsiveness with very short timeouts. | |
| 352 | + */ | |
| 353 | + static final long spinForTimeoutThreshold = 1000L; | |
| 354 | + | |
| 355 | + /** | |
| 356 | + * Inserts node into queue, initializing if necessary. See picture above. | |
| 357 | + * @param node the node to insert | |
| 358 | + * @return node's predecessor | |
| 359 | + */ | |
| 360 | + private Node enq(final Node node) { | |
| 361 | + for (;;) { | |
| 362 | + Node t = tail; | |
| 363 | + if (t == null) { // Must initialize | |
| 364 | + if (compareAndSetHead(new Node())) | |
| 365 | + tail = head; | |
| 366 | + } else { | |
| 367 | + node.prev = t; | |
| 368 | + if (compareAndSetTail(t, node)) { | |
| 369 | + t.next = node; | |
| 370 | + return t; | |
| 371 | + } | |
| 372 | + } | |
| 373 | + } | |
| 374 | + } | |
| 375 | + | |
| 376 | + /** | |
| 377 | + * Creates and enqueues node for current thread and given mode. | |
| 378 | + * | |
| 379 | + * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared | |
| 380 | + * @return the new node | |
| 381 | + */ | |
| 382 | + private Node addWaiter(Node mode) { | |
| 383 | + Node node = new Node(Thread.currentThread(), mode); | |
| 384 | + // Try the fast path of enq; backup to full enq on failure | |
| 385 | + Node pred = tail; | |
| 386 | + if (pred != null) { | |
| 387 | + node.prev = pred; | |
| 388 | + if (compareAndSetTail(pred, node)) { | |
| 389 | + pred.next = node; | |
| 390 | + return node; | |
| 391 | + } | |
| 392 | + } | |
| 393 | + enq(node); | |
| 394 | + return node; | |
| 395 | + } | |
| 396 | + | |
| 397 | + /** | |
| 398 | + * Sets head of queue to be node, thus dequeuing. Called only by | |
| 399 | + * acquire methods. Also nulls out unused fields for sake of GC | |
| 400 | + * and to suppress unnecessary signals and traversals. | |
| 401 | + * | |
| 402 | + * @param node the node | |
| 403 | + */ | |
| 404 | + private void setHead(Node node) { | |
| 405 | + head = node; | |
| 406 | + node.thread = null; | |
| 407 | + node.prev = null; | |
| 408 | + } | |
| 409 | + | |
| 410 | + /** | |
| 411 | + * Wakes up node's successor, if one exists. | |
| 412 | + * | |
| 413 | + * @param node the node | |
| 414 | + */ | |
| 415 | + private void unparkSuccessor(Node node) { | |
| 416 | + /* | |
| 417 | + * If status is negative (i.e., possibly needing signal) try | |
| 418 | + * to clear in anticipation of signalling. It is OK if this | |
| 419 | + * fails or if status is changed by waiting thread. | |
| 420 | + */ | |
| 421 | + int ws = node.waitStatus; | |
| 422 | + if (ws < 0) | |
| 423 | + compareAndSetWaitStatus(node, ws, 0); | |
| 424 | + | |
| 425 | + /* | |
| 426 | + * Thread to unpark is held in successor, which is normally | |
| 427 | + * just the next node. But if cancelled or apparently null, | |
| 428 | + * traverse backwards from tail to find the actual | |
| 429 | + * non-cancelled successor. | |
| 430 | + */ | |
| 431 | + Node s = node.next; | |
| 432 | + if (s == null || s.waitStatus > 0) { | |
| 433 | + s = null; | |
| 434 | + for (Node t = tail; t != null && t != node; t = t.prev) | |
| 435 | + if (t.waitStatus <= 0) | |
| 436 | + s = t; | |
| 437 | + } | |
| 438 | + if (s != null) | |
| 439 | + LockSupport.unpark(s.thread); | |
| 440 | + } | |
| 441 | + | |
| 442 | + /** | |
| 443 | + * Release action for shared mode -- signal successor and ensure | |
| 444 | + * propagation. (Note: For exclusive mode, release just amounts | |
| 445 | + * to calling unparkSuccessor of head if it needs signal.) | |
| 446 | + */ | |
| 447 | + private void doReleaseShared() { | |
| 448 | + /* | |
| 449 | + * Ensure that a release propagates, even if there are other | |
| 450 | + * in-progress acquires/releases. This proceeds in the usual | |
| 451 | + * way of trying to unparkSuccessor of head if it needs | |
| 452 | + * signal. But if it does not, status is set to PROPAGATE to | |
| 453 | + * ensure that upon release, propagation continues. | |
| 454 | + * Additionally, we must loop in case a new node is added | |
| 455 | + * while we are doing this. Also, unlike other uses of | |
| 456 | + * unparkSuccessor, we need to know if CAS to reset status | |
| 457 | + * fails, if so rechecking. | |
| 458 | + */ | |
| 459 | + for (;;) { | |
| 460 | + Node h = head; | |
| 461 | + if (h != null && h != tail) { | |
| 462 | + int ws = h.waitStatus; | |
| 463 | + if (ws == Node.SIGNAL) { | |
| 464 | + if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) | |
| 465 | + continue; // loop to recheck cases | |
| 466 | + unparkSuccessor(h); | |
| 467 | + } | |
| 468 | + else if (ws == 0 && | |
| 469 | + !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) | |
| 470 | + continue; // loop on failed CAS | |
| 471 | + } | |
| 472 | + if (h == head) // loop if head changed | |
| 473 | + break; | |
| 474 | + } | |
| 475 | + } | |
| 476 | + | |
| 477 | + /** | |
| 478 | + * Sets head of queue, and checks if successor may be waiting | |
| 479 | + * in shared mode, if so propagating if either propagate > 0 or | |
| 480 | + * PROPAGATE status was set. | |
| 481 | + * | |
| 482 | + * @param node the node | |
| 483 | + * @param propagate the return value from a tryAcquireShared | |
| 484 | + */ | |
| 485 | + private void setHeadAndPropagate(Node node, long propagate) { | |
| 486 | + Node h = head; // Record old head for check below | |
| 487 | + setHead(node); | |
| 488 | + /* | |
| 489 | + * Try to signal next queued node if: | |
| 490 | + * Propagation was indicated by caller, | |
| 491 | + * or was recorded (as h.waitStatus) by a previous operation | |
| 492 | + * (note: this uses sign-check of waitStatus because | |
| 493 | + * PROPAGATE status may transition to SIGNAL.) | |
| 494 | + * and | |
| 495 | + * The next node is waiting in shared mode, | |
| 496 | + * or we don't know, because it appears null | |
| 497 | + * | |
| 498 | + * The conservatism in both of these checks may cause | |
| 499 | + * unnecessary wake-ups, but only when there are multiple | |
| 500 | + * racing acquires/releases, so most need signals now or soon | |
| 501 | + * anyway. | |
| 502 | + */ | |
| 503 | + if (propagate > 0 || h == null || h.waitStatus < 0) { | |
| 504 | + Node s = node.next; | |
| 505 | + if (s == null || s.isShared()) | |
| 506 | + doReleaseShared(); | |
| 507 | + } | |
| 508 | + } | |
| 509 | + | |
| 510 | + // Utilities for various versions of acquire | |
| 511 | + | |
| 512 | + /** | |
| 513 | + * Cancels an ongoing attempt to acquire. | |
| 514 | + * | |
| 515 | + * @param node the node | |
| 516 | + */ | |
| 517 | + private void cancelAcquire(Node node) { | |
| 518 | + // Ignore if node doesn't exist | |
| 519 | + if (node == null) | |
| 520 | + return; | |
| 521 | + | |
| 522 | + node.thread = null; | |
| 523 | + | |
| 524 | + // Skip cancelled predecessors | |
| 525 | + Node pred = node.prev; | |
| 526 | + while (pred.waitStatus > 0) | |
| 527 | + node.prev = pred = pred.prev; | |
| 528 | + | |
| 529 | + // predNext is the apparent node to unsplice. CASes below will | |
| 530 | + // fail if not, in which case, we lost race vs another cancel | |
| 531 | + // or signal, so no further action is necessary. | |
| 532 | + Node predNext = pred.next; | |
| 533 | + | |
| 534 | + // Can use unconditional write instead of CAS here. | |
| 535 | + // After this atomic step, other Nodes can skip past us. | |
| 536 | + // Before, we are free of interference from other threads. | |
| 537 | + node.waitStatus = Node.CANCELLED; | |
| 538 | + | |
| 539 | + // If we are the tail, remove ourselves. | |
| 540 | + if (node == tail && compareAndSetTail(node, pred)) { | |
| 541 | + compareAndSetNext(pred, predNext, null); | |
| 542 | + } else { | |
| 543 | + // If successor needs signal, try to set pred's next-link | |
| 544 | + // so it will get one. Otherwise wake it up to propagate. | |
| 545 | + int ws; | |
| 546 | + if (pred != head && | |
| 547 | + ((ws = pred.waitStatus) == Node.SIGNAL || | |
| 548 | + (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) && | |
| 549 | + pred.thread != null) { | |
| 550 | + Node next = node.next; | |
| 551 | + if (next != null && next.waitStatus <= 0) | |
| 552 | + compareAndSetNext(pred, predNext, next); | |
| 553 | + } else { | |
| 554 | + unparkSuccessor(node); | |
| 555 | + } | |
| 556 | + | |
| 557 | + node.next = node; // help GC | |
| 558 | + } | |
| 559 | + } | |
| 560 | + | |
| 561 | + /** | |
| 562 | + * Checks and updates status for a node that failed to acquire. | |
| 563 | + * Returns true if thread should block. This is the main signal | |
| 564 | + * control in all acquire loops. Requires that pred == node.prev | |
| 565 | + * | |
| 566 | + * @param pred node's predecessor holding status | |
| 567 | + * @param node the node | |
| 568 | + * @return {@code true} if thread should block | |
| 569 | + */ | |
| 570 | + private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) { | |
| 571 | + int ws = pred.waitStatus; | |
| 572 | + if (ws == Node.SIGNAL) | |
| 573 | + /* | |
| 574 | + * This node has already set status asking a release | |
| 575 | + * to signal it, so it can safely park. | |
| 576 | + */ | |
| 577 | + return true; | |
| 578 | + if (ws > 0) { | |
| 579 | + /* | |
| 580 | + * Predecessor was cancelled. Skip over predecessors and | |
| 581 | + * indicate retry. | |
| 582 | + */ | |
| 583 | + do { | |
| 584 | + node.prev = pred = pred.prev; | |
| 585 | + } while (pred.waitStatus > 0); | |
| 586 | + pred.next = node; | |
| 587 | + } else { | |
| 588 | + /* | |
| 589 | + * waitStatus must be 0 or PROPAGATE. Indicate that we | |
| 590 | + * need a signal, but don't park yet. Caller will need to | |
| 591 | + * retry to make sure it cannot acquire before parking. | |
| 592 | + */ | |
| 593 | + compareAndSetWaitStatus(pred, ws, Node.SIGNAL); | |
| 594 | + } | |
| 595 | + return false; | |
| 596 | + } | |
| 597 | + | |
| 598 | + /** | |
| 599 | + * Convenience method to interrupt current thread. | |
| 600 | + */ | |
| 601 | + private static void selfInterrupt() { | |
| 602 | + Thread.currentThread().interrupt(); | |
| 603 | + } | |
| 604 | + | |
| 605 | + /** | |
| 606 | + * Convenience method to park and then check if interrupted | |
| 607 | + * | |
| 608 | + * @return {@code true} if interrupted | |
| 609 | + */ | |
| 610 | + private final boolean parkAndCheckInterrupt() { | |
| 611 | + LockSupport.park(this); | |
| 612 | + return Thread.interrupted(); | |
| 613 | + } | |
| 614 | + | |
| 615 | + /* | |
| 616 | + * Various flavors of acquire, varying in exclusive/shared and | |
| 617 | + * control modes. Each is mostly the same, but annoyingly | |
| 618 | + * different. Only a little bit of factoring is possible due to | |
| 619 | + * interactions of exception mechanics (including ensuring that we | |
| 620 | + * cancel if tryAcquire throws exception) and other control, at | |
| 621 | + * least not without hurting performance too much. | |
| 622 | + */ | |
| 623 | + | |
| 624 | + /** | |
| 625 | + * Acquires in exclusive uninterruptible mode for thread already in | |
| 626 | + * queue. Used by condition wait methods as well as acquire. | |
| 627 | + * | |
| 628 | + * @param node the node | |
| 629 | + * @param arg the acquire argument | |
| 630 | + * @return {@code true} if interrupted while waiting | |
| 631 | + */ | |
| 632 | + final boolean acquireQueued(final Node node, long arg) { | |
| 633 | + boolean failed = true; | |
| 634 | + try { | |
| 635 | + boolean interrupted = false; | |
| 636 | + for (;;) { | |
| 637 | + final Node p = node.predecessor(); | |
| 638 | + if (p == head && tryAcquire(arg)) { | |
| 639 | + setHead(node); | |
| 640 | + p.next = null; // help GC | |
| 641 | + failed = false; | |
| 642 | + return interrupted; | |
| 643 | + } | |
| 644 | + if (shouldParkAfterFailedAcquire(p, node) && | |
| 645 | + parkAndCheckInterrupt()) | |
| 646 | + interrupted = true; | |
| 647 | + } | |
| 648 | + } finally { | |
| 649 | + if (failed) | |
| 650 | + cancelAcquire(node); | |
| 651 | + } | |
| 652 | + } | |
| 653 | + | |
| 654 | + /** | |
| 655 | + * Acquires in exclusive interruptible mode. | |
| 656 | + * @param arg the acquire argument | |
| 657 | + */ | |
| 658 | + private void doAcquireInterruptibly(long arg) | |
| 659 | + throws InterruptedException { | |
| 660 | + final Node node = addWaiter(Node.EXCLUSIVE); | |
| 661 | + boolean failed = true; | |
| 662 | + try { | |
| 663 | + for (;;) { | |
| 664 | + final Node p = node.predecessor(); | |
| 665 | + if (p == head && tryAcquire(arg)) { | |
| 666 | + setHead(node); | |
| 667 | + p.next = null; // help GC | |
| 668 | + failed = false; | |
| 669 | + return; | |
| 670 | + } | |
| 671 | + if (shouldParkAfterFailedAcquire(p, node) && | |
| 672 | + parkAndCheckInterrupt()) | |
| 673 | + throw new InterruptedException(); | |
| 674 | + } | |
| 675 | + } finally { | |
| 676 | + if (failed) | |
| 677 | + cancelAcquire(node); | |
| 678 | + } | |
| 679 | + } | |
| 680 | + | |
| 681 | + /** | |
| 682 | + * Acquires in exclusive timed mode. | |
| 683 | + * | |
| 684 | + * @param arg the acquire argument | |
| 685 | + * @param nanosTimeout max wait time | |
| 686 | + * @return {@code true} if acquired | |
| 687 | + */ | |
| 688 | + private boolean doAcquireNanos(long arg, long nanosTimeout) | |
| 689 | + throws InterruptedException { | |
| 690 | + long lastTime = System.nanoTime(); | |
| 691 | + final Node node = addWaiter(Node.EXCLUSIVE); | |
| 692 | + boolean failed = true; | |
| 693 | + try { | |
| 694 | + for (;;) { | |
| 695 | + final Node p = node.predecessor(); | |
| 696 | + if (p == head && tryAcquire(arg)) { | |
| 697 | + setHead(node); | |
| 698 | + p.next = null; // help GC | |
| 699 | + failed = false; | |
| 700 | + return true; | |
| 701 | + } | |
| 702 | + if (nanosTimeout <= 0) | |
| 703 | + return false; | |
| 704 | + if (shouldParkAfterFailedAcquire(p, node) && | |
| 705 | + nanosTimeout > spinForTimeoutThreshold) | |
| 706 | + LockSupport.parkNanos(this, nanosTimeout); | |
| 707 | + long now = System.nanoTime(); | |
| 708 | + nanosTimeout -= now - lastTime; | |
| 709 | + lastTime = now; | |
| 710 | + if (Thread.interrupted()) | |
| 711 | + throw new InterruptedException(); | |
| 712 | + } | |
| 713 | + } finally { | |
| 714 | + if (failed) | |
| 715 | + cancelAcquire(node); | |
| 716 | + } | |
| 717 | + } | |
| 718 | + | |
| 719 | + /** | |
| 720 | + * Acquires in shared uninterruptible mode. | |
| 721 | + * @param arg the acquire argument | |
| 722 | + */ | |
| 723 | + private void doAcquireShared(long arg) { | |
| 724 | + final Node node = addWaiter(Node.SHARED); | |
| 725 | + boolean failed = true; | |
| 726 | + try { | |
| 727 | + boolean interrupted = false; | |
| 728 | + for (;;) { | |
| 729 | + final Node p = node.predecessor(); | |
| 730 | + if (p == head) { | |
| 731 | + long r = tryAcquireShared(arg); | |
| 732 | + if (r >= 0) { | |
| 733 | + setHeadAndPropagate(node, r); | |
| 734 | + p.next = null; // help GC | |
| 735 | + if (interrupted) | |
| 736 | + selfInterrupt(); | |
| 737 | + failed = false; | |
| 738 | + return; | |
| 739 | + } | |
| 740 | + } | |
| 741 | + if (shouldParkAfterFailedAcquire(p, node) && | |
| 742 | + parkAndCheckInterrupt()) | |
| 743 | + interrupted = true; | |
| 744 | + } | |
| 745 | + } finally { | |
| 746 | + if (failed) | |
| 747 | + cancelAcquire(node); | |
| 748 | + } | |
| 749 | + } | |
| 750 | + | |
| 751 | + /** | |
| 752 | + * Acquires in shared interruptible mode. | |
| 753 | + * @param arg the acquire argument | |
| 754 | + */ | |
| 755 | + private void doAcquireSharedInterruptibly(long arg) | |
| 756 | + throws InterruptedException { | |
| 757 | + final Node node = addWaiter(Node.SHARED); | |
| 758 | + boolean failed = true; | |
| 759 | + try { | |
| 760 | + for (;;) { | |
| 761 | + final Node p = node.predecessor(); | |
| 762 | + if (p == head) { | |
| 763 | + long r = tryAcquireShared(arg); | |
| 764 | + if (r >= 0) { | |
| 765 | + setHeadAndPropagate(node, r); | |
| 766 | + p.next = null; // help GC | |
| 767 | + failed = false; | |
| 768 | + return; | |
| 769 | + } | |
| 770 | + } | |
| 771 | + if (shouldParkAfterFailedAcquire(p, node) && | |
| 772 | + parkAndCheckInterrupt()) | |
| 773 | + throw new InterruptedException(); | |
| 774 | + } | |
| 775 | + } finally { | |
| 776 | + if (failed) | |
| 777 | + cancelAcquire(node); | |
| 778 | + } | |
| 779 | + } | |
| 780 | + | |
| 781 | + /** | |
| 782 | + * Acquires in shared timed mode. | |
| 783 | + * | |
| 784 | + * @param arg the acquire argument | |
| 785 | + * @param nanosTimeout max wait time | |
| 786 | + * @return {@code true} if acquired | |
| 787 | + */ | |
| 788 | + private boolean doAcquireSharedNanos(long arg, long nanosTimeout) | |
| 789 | + throws InterruptedException { | |
| 790 | + | |
| 791 | + long lastTime = System.nanoTime(); | |
| 792 | + final Node node = addWaiter(Node.SHARED); | |
| 793 | + boolean failed = true; | |
| 794 | + try { | |
| 795 | + for (;;) { | |
| 796 | + final Node p = node.predecessor(); | |
| 797 | + if (p == head) { | |
| 798 | + long r = tryAcquireShared(arg); | |
| 799 | + if (r >= 0) { | |
| 800 | + setHeadAndPropagate(node, r); | |
| 801 | + p.next = null; // help GC | |
| 802 | + failed = false; | |
| 803 | + return true; | |
| 804 | + } | |
| 805 | + } | |
| 806 | + if (nanosTimeout <= 0) | |
| 807 | + return false; | |
| 808 | + if (shouldParkAfterFailedAcquire(p, node) && | |
| 809 | + nanosTimeout > spinForTimeoutThreshold) | |
| 810 | + LockSupport.parkNanos(this, nanosTimeout); | |
| 811 | + long now = System.nanoTime(); | |
| 812 | + nanosTimeout -= now - lastTime; | |
| 813 | + lastTime = now; | |
| 814 | + if (Thread.interrupted()) | |
| 815 | + throw new InterruptedException(); | |
| 816 | + } | |
| 817 | + } finally { | |
| 818 | + if (failed) | |
| 819 | + cancelAcquire(node); | |
| 820 | + } | |
| 821 | + } | |
| 822 | + | |
| 823 | + // Main exported methods | |
| 824 | + | |
| 825 | + /** | |
| 826 | + * Attempts to acquire in exclusive mode. This method should query | |
| 827 | + * if the state of the object permits it to be acquired in the | |
| 828 | + * exclusive mode, and if so to acquire it. | |
| 829 | + * | |
| 830 | + * <p>This method is always invoked by the thread performing | |
| 831 | + * acquire. If this method reports failure, the acquire method | |
| 832 | + * may queue the thread, if it is not already queued, until it is | |
| 833 | + * signalled by a release from some other thread. This can be used | |
| 834 | + * to implement method {@link Lock#tryLock()}. | |
| 835 | + * | |
| 836 | + * <p>The default | |
| 837 | + * implementation throws {@link UnsupportedOperationException}. | |
| 838 | + * | |
| 839 | + * @param arg the acquire argument. This value is always the one | |
| 840 | + * passed to an acquire method, or is the value saved on entry | |
| 841 | + * to a condition wait. The value is otherwise uninterpreted | |
| 842 | + * and can represent anything you like. | |
| 843 | + * @return {@code true} if successful. Upon success, this object has | |
| 844 | + * been acquired. | |
| 845 | + * @throws IllegalMonitorStateException if acquiring would place this | |
| 846 | + * synchronizer in an illegal state. This exception must be | |
| 847 | + * thrown in a consistent fashion for synchronization to work | |
| 848 | + * correctly. | |
| 849 | + * @throws UnsupportedOperationException if exclusive mode is not supported | |
| 850 | + */ | |
| 851 | + protected boolean tryAcquire(long arg) { | |
| 852 | + throw new UnsupportedOperationException(); | |
| 853 | + } | |
| 854 | + | |
| 855 | + /** | |
| 856 | + * Attempts to set the state to reflect a release in exclusive | |
| 857 | + * mode. | |
| 858 | + * | |
| 859 | + * <p>This method is always invoked by the thread performing release. | |
| 860 | + * | |
| 861 | + * <p>The default implementation throws | |
| 862 | + * {@link UnsupportedOperationException}. | |
| 863 | + * | |
| 864 | + * @param arg the release argument. This value is always the one | |
| 865 | + * passed to a release method, or the current state value upon | |
| 866 | + * entry to a condition wait. The value is otherwise | |
| 867 | + * uninterpreted and can represent anything you like. | |
| 868 | + * @return {@code true} if this object is now in a fully released | |
| 869 | + * state, so that any waiting threads may attempt to acquire; | |
| 870 | + * and {@code false} otherwise. | |
| 871 | + * @throws IllegalMonitorStateException if releasing would place this | |
| 872 | + * synchronizer in an illegal state. This exception must be | |
| 873 | + * thrown in a consistent fashion for synchronization to work | |
| 874 | + * correctly. | |
| 875 | + * @throws UnsupportedOperationException if exclusive mode is not supported | |
| 876 | + */ | |
| 877 | + protected boolean tryRelease(long arg) { | |
| 878 | + throw new UnsupportedOperationException(); | |
| 879 | + } | |
| 880 | + | |
| 881 | + /** | |
| 882 | + * Attempts to acquire in shared mode. This method should query if | |
| 883 | + * the state of the object permits it to be acquired in the shared | |
| 884 | + * mode, and if so to acquire it. | |
| 885 | + * | |
| 886 | + * <p>This method is always invoked by the thread performing | |
| 887 | + * acquire. If this method reports failure, the acquire method | |
| 888 | + * may queue the thread, if it is not already queued, until it is | |
| 889 | + * signalled by a release from some other thread. | |
| 890 | + * | |
| 891 | + * <p>The default implementation throws {@link | |
| 892 | + * UnsupportedOperationException}. | |
| 893 | + * | |
| 894 | + * @param arg the acquire argument. This value is always the one | |
| 895 | + * passed to an acquire method, or is the value saved on entry | |
| 896 | + * to a condition wait. The value is otherwise uninterpreted | |
| 897 | + * and can represent anything you like. | |
| 898 | + * @return a negative value on failure; zero if acquisition in shared | |
| 899 | + * mode succeeded but no subsequent shared-mode acquire can | |
| 900 | + * succeed; and a positive value if acquisition in shared | |
| 901 | + * mode succeeded and subsequent shared-mode acquires might | |
| 902 | + * also succeed, in which case a subsequent waiting thread | |
| 903 | + * must check availability. (Support for three different | |
| 904 | + * return values enables this method to be used in contexts | |
| 905 | + * where acquires only sometimes act exclusively.) Upon | |
| 906 | + * success, this object has been acquired. | |
| 907 | + * @throws IllegalMonitorStateException if acquiring would place this | |
| 908 | + * synchronizer in an illegal state. This exception must be | |
| 909 | + * thrown in a consistent fashion for synchronization to work | |
| 910 | + * correctly. | |
| 911 | + * @throws UnsupportedOperationException if shared mode is not supported | |
| 912 | + */ | |
| 913 | + protected long tryAcquireShared(long arg) { | |
| 914 | + throw new UnsupportedOperationException(); | |
| 915 | + } | |
| 916 | + | |
| 917 | + /** | |
| 918 | + * Attempts to set the state to reflect a release in shared mode. | |
| 919 | + * | |
| 920 | + * <p>This method is always invoked by the thread performing release. | |
| 921 | + * | |
| 922 | + * <p>The default implementation throws | |
| 923 | + * {@link UnsupportedOperationException}. | |
| 924 | + * | |
| 925 | + * @param arg the release argument. This value is always the one | |
| 926 | + * passed to a release method, or the current state value upon | |
| 927 | + * entry to a condition wait. The value is otherwise | |
| 928 | + * uninterpreted and can represent anything you like. | |
| 929 | + * @return {@code true} if this release of shared mode may permit a | |
| 930 | + * waiting acquire (shared or exclusive) to succeed; and | |
| 931 | + * {@code false} otherwise | |
| 932 | + * @throws IllegalMonitorStateException if releasing would place this | |
| 933 | + * synchronizer in an illegal state. This exception must be | |
| 934 | + * thrown in a consistent fashion for synchronization to work | |
| 935 | + * correctly. | |
| 936 | + * @throws UnsupportedOperationException if shared mode is not supported | |
| 937 | + */ | |
| 938 | + protected boolean tryReleaseShared(long arg) { | |
| 939 | + throw new UnsupportedOperationException(); | |
| 940 | + } | |
| 941 | + | |
| 942 | + /** | |
| 943 | + * Returns {@code true} if synchronization is held exclusively with | |
| 944 | + * respect to the current (calling) thread. This method is invoked | |
| 945 | + * upon each call to a non-waiting {@link ConditionObject} method. | |
| 946 | + * (Waiting methods instead invoke {@link #release}.) | |
| 947 | + * | |
| 948 | + * <p>The default implementation throws {@link | |
| 949 | + * UnsupportedOperationException}. This method is invoked | |
| 950 | + * internally only within {@link ConditionObject} methods, so need | |
| 951 | + * not be defined if conditions are not used. | |
| 952 | + * | |
| 953 | + * @return {@code true} if synchronization is held exclusively; | |
| 954 | + * {@code false} otherwise | |
| 955 | + * @throws UnsupportedOperationException if conditions are not supported | |
| 956 | + */ | |
| 957 | + protected boolean isHeldExclusively() { | |
| 958 | + throw new UnsupportedOperationException(); | |
| 959 | + } | |
| 960 | + | |
| 961 | + /** | |
| 962 | + * Acquires in exclusive mode, ignoring interrupts. Implemented | |
| 963 | + * by invoking at least once {@link #tryAcquire}, | |
| 964 | + * returning on success. Otherwise the thread is queued, possibly | |
| 965 | + * repeatedly blocking and unblocking, invoking {@link | |
| 966 | + * #tryAcquire} until success. This method can be used | |
| 967 | + * to implement method {@link Lock#lock}. | |
| 968 | + * | |
| 969 | + * @param arg the acquire argument. This value is conveyed to | |
| 970 | + * {@link #tryAcquire} but is otherwise uninterpreted and | |
| 971 | + * can represent anything you like. | |
| 972 | + */ | |
| 973 | + public final void acquire(long arg) { | |
| 974 | + if (!tryAcquire(arg) && | |
| 975 | + acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) | |
| 976 | + selfInterrupt(); | |
| 977 | + } | |
| 978 | + | |
| 979 | + /** | |
| 980 | + * Acquires in exclusive mode, aborting if interrupted. | |
| 981 | + * Implemented by first checking interrupt status, then invoking | |
| 982 | + * at least once {@link #tryAcquire}, returning on | |
| 983 | + * success. Otherwise the thread is queued, possibly repeatedly | |
| 984 | + * blocking and unblocking, invoking {@link #tryAcquire} | |
| 985 | + * until success or the thread is interrupted. This method can be | |
| 986 | + * used to implement method {@link Lock#lockInterruptibly}. | |
| 987 | + * | |
| 988 | + * @param arg the acquire argument. This value is conveyed to | |
| 989 | + * {@link #tryAcquire} but is otherwise uninterpreted and | |
| 990 | + * can represent anything you like. | |
| 991 | + * @throws InterruptedException if the current thread is interrupted | |
| 992 | + */ | |
| 993 | + public final void acquireInterruptibly(long arg) | |
| 994 | + throws InterruptedException { | |
| 995 | + if (Thread.interrupted()) | |
| 996 | + throw new InterruptedException(); | |
| 997 | + if (!tryAcquire(arg)) | |
| 998 | + doAcquireInterruptibly(arg); | |
| 999 | + } | |
| 1000 | + | |
| 1001 | + /** | |
| 1002 | + * Attempts to acquire in exclusive mode, aborting if interrupted, | |
| 1003 | + * and failing if the given timeout elapses. Implemented by first | |
| 1004 | + * checking interrupt status, then invoking at least once {@link | |
| 1005 | + * #tryAcquire}, returning on success. Otherwise, the thread is | |
| 1006 | + * queued, possibly repeatedly blocking and unblocking, invoking | |
| 1007 | + * {@link #tryAcquire} until success or the thread is interrupted | |
| 1008 | + * or the timeout elapses. This method can be used to implement | |
| 1009 | + * method {@link Lock#tryLock(long, TimeUnit)}. | |
| 1010 | + * | |
| 1011 | + * @param arg the acquire argument. This value is conveyed to | |
| 1012 | + * {@link #tryAcquire} but is otherwise uninterpreted and | |
| 1013 | + * can represent anything you like. | |
| 1014 | + * @param nanosTimeout the maximum number of nanoseconds to wait | |
| 1015 | + * @return {@code true} if acquired; {@code false} if timed out | |
| 1016 | + * @throws InterruptedException if the current thread is interrupted | |
| 1017 | + */ | |
| 1018 | + public final boolean tryAcquireNanos(long arg, long nanosTimeout) | |
| 1019 | + throws InterruptedException { | |
| 1020 | + if (Thread.interrupted()) | |
| 1021 | + throw new InterruptedException(); | |
| 1022 | + return tryAcquire(arg) || | |
| 1023 | + doAcquireNanos(arg, nanosTimeout); | |
| 1024 | + } | |
| 1025 | + | |
| 1026 | + /** | |
| 1027 | + * Releases in exclusive mode. Implemented by unblocking one or | |
| 1028 | + * more threads if {@link #tryRelease} returns true. | |
| 1029 | + * This method can be used to implement method {@link Lock#unlock}. | |
| 1030 | + * | |
| 1031 | + * @param arg the release argument. This value is conveyed to | |
| 1032 | + * {@link #tryRelease} but is otherwise uninterpreted and | |
| 1033 | + * can represent anything you like. | |
| 1034 | + * @return the value returned from {@link #tryRelease} | |
| 1035 | + */ | |
| 1036 | + public final boolean release(long arg) { | |
| 1037 | + if (tryRelease(arg)) { | |
| 1038 | + Node h = head; | |
| 1039 | + if (h != null && h.waitStatus != 0) | |
| 1040 | + unparkSuccessor(h); | |
| 1041 | + return true; | |
| 1042 | + } | |
| 1043 | + return false; | |
| 1044 | + } | |
| 1045 | + | |
| 1046 | + /** | |
| 1047 | + * Acquires in shared mode, ignoring interrupts. Implemented by | |
| 1048 | + * first invoking at least once {@link #tryAcquireShared}, | |
| 1049 | + * returning on success. Otherwise the thread is queued, possibly | |
| 1050 | + * repeatedly blocking and unblocking, invoking {@link | |
| 1051 | + * #tryAcquireShared} until success. | |
| 1052 | + * | |
| 1053 | + * @param arg the acquire argument. This value is conveyed to | |
| 1054 | + * {@link #tryAcquireShared} but is otherwise uninterpreted | |
| 1055 | + * and can represent anything you like. | |
| 1056 | + */ | |
| 1057 | + public final void acquireShared(long arg) { | |
| 1058 | + if (tryAcquireShared(arg) < 0) | |
| 1059 | + doAcquireShared(arg); | |
| 1060 | + } | |
| 1061 | + | |
| 1062 | + /** | |
| 1063 | + * Acquires in shared mode, aborting if interrupted. Implemented | |
| 1064 | + * by first checking interrupt status, then invoking at least once | |
| 1065 | + * {@link #tryAcquireShared}, returning on success. Otherwise the | |
| 1066 | + * thread is queued, possibly repeatedly blocking and unblocking, | |
| 1067 | + * invoking {@link #tryAcquireShared} until success or the thread | |
| 1068 | + * is interrupted. | |
| 1069 | + * @param arg the acquire argument | |
| 1070 | + * This value is conveyed to {@link #tryAcquireShared} but is | |
| 1071 | + * otherwise uninterpreted and can represent anything | |
| 1072 | + * you like. | |
| 1073 | + * @throws InterruptedException if the current thread is interrupted | |
| 1074 | + */ | |
| 1075 | + public final void acquireSharedInterruptibly(long arg) | |
| 1076 | + throws InterruptedException { | |
| 1077 | + if (Thread.interrupted()) | |
| 1078 | + throw new InterruptedException(); | |
| 1079 | + if (tryAcquireShared(arg) < 0) | |
| 1080 | + doAcquireSharedInterruptibly(arg); | |
| 1081 | + } | |
| 1082 | + | |
| 1083 | + /** | |
| 1084 | + * Attempts to acquire in shared mode, aborting if interrupted, and | |
| 1085 | + * failing if the given timeout elapses. Implemented by first | |
| 1086 | + * checking interrupt status, then invoking at least once {@link | |
| 1087 | + * #tryAcquireShared}, returning on success. Otherwise, the | |
| 1088 | + * thread is queued, possibly repeatedly blocking and unblocking, | |
| 1089 | + * invoking {@link #tryAcquireShared} until success or the thread | |
| 1090 | + * is interrupted or the timeout elapses. | |
| 1091 | + * | |
| 1092 | + * @param arg the acquire argument. This value is conveyed to | |
| 1093 | + * {@link #tryAcquireShared} but is otherwise uninterpreted | |
| 1094 | + * and can represent anything you like. | |
| 1095 | + * @param nanosTimeout the maximum number of nanoseconds to wait | |
| 1096 | + * @return {@code true} if acquired; {@code false} if timed out | |
| 1097 | + * @throws InterruptedException if the current thread is interrupted | |
| 1098 | + */ | |
| 1099 | + public final boolean tryAcquireSharedNanos(long arg, long nanosTimeout) | |
| 1100 | + throws InterruptedException { | |
| 1101 | + if (Thread.interrupted()) | |
| 1102 | + throw new InterruptedException(); | |
| 1103 | + return tryAcquireShared(arg) >= 0 || | |
| 1104 | + doAcquireSharedNanos(arg, nanosTimeout); | |
| 1105 | + } | |
| 1106 | + | |
| 1107 | + /** | |
| 1108 | + * Releases in shared mode. Implemented by unblocking one or more | |
| 1109 | + * threads if {@link #tryReleaseShared} returns true. | |
| 1110 | + * | |
| 1111 | + * @param arg the release argument. This value is conveyed to | |
| 1112 | + * {@link #tryReleaseShared} but is otherwise uninterpreted | |
| 1113 | + * and can represent anything you like. | |
| 1114 | + * @return the value returned from {@link #tryReleaseShared} | |
| 1115 | + */ | |
| 1116 | + public final boolean releaseShared(long arg) { | |
| 1117 | + if (tryReleaseShared(arg)) { | |
| 1118 | + doReleaseShared(); | |
| 1119 | + return true; | |
| 1120 | + } | |
| 1121 | + return false; | |
| 1122 | + } | |
| 1123 | + | |
| 1124 | + // Queue inspection methods | |
| 1125 | + | |
| 1126 | + /** | |
| 1127 | + * Queries whether any threads are waiting to acquire. Note that | |
| 1128 | + * because cancellations due to interrupts and timeouts may occur | |
| 1129 | + * at any time, a {@code true} return does not guarantee that any | |
| 1130 | + * other thread will ever acquire. | |
| 1131 | + * | |
| 1132 | + * <p>In this implementation, this operation returns in | |
| 1133 | + * constant time. | |
| 1134 | + * | |
| 1135 | + * @return {@code true} if there may be other threads waiting to acquire | |
| 1136 | + */ | |
| 1137 | + public final boolean hasQueuedThreads() { | |
| 1138 | + return head != tail; | |
| 1139 | + } | |
| 1140 | + | |
| 1141 | + /** | |
| 1142 | + * Queries whether any threads have ever contended to acquire this | |
| 1143 | + * synchronizer; that is if an acquire method has ever blocked. | |
| 1144 | + * | |
| 1145 | + * <p>In this implementation, this operation returns in | |
| 1146 | + * constant time. | |
| 1147 | + * | |
| 1148 | + * @return {@code true} if there has ever been contention | |
| 1149 | + */ | |
| 1150 | + public final boolean hasContended() { | |
| 1151 | + return head != null; | |
| 1152 | + } | |
| 1153 | + | |
| 1154 | + /** | |
| 1155 | + * Returns the first (longest-waiting) thread in the queue, or | |
| 1156 | + * {@code null} if no threads are currently queued. | |
| 1157 | + * | |
| 1158 | + * <p>In this implementation, this operation normally returns in | |
| 1159 | + * constant time, but may iterate upon contention if other threads are | |
| 1160 | + * concurrently modifying the queue. | |
| 1161 | + * | |
| 1162 | + * @return the first (longest-waiting) thread in the queue, or | |
| 1163 | + * {@code null} if no threads are currently queued | |
| 1164 | + */ | |
| 1165 | + public final Thread getFirstQueuedThread() { | |
| 1166 | + // handle only fast path, else relay | |
| 1167 | + return (head == tail) ? null : fullGetFirstQueuedThread(); | |
| 1168 | + } | |
| 1169 | + | |
| 1170 | + /** | |
| 1171 | + * Version of getFirstQueuedThread called when fastpath fails | |
| 1172 | + */ | |
| 1173 | + private Thread fullGetFirstQueuedThread() { | |
| 1174 | + /* | |
| 1175 | + * The first node is normally head.next. Try to get its | |
| 1176 | + * thread field, ensuring consistent reads: If thread | |
| 1177 | + * field is nulled out or s.prev is no longer head, then | |
| 1178 | + * some other thread(s) concurrently performed setHead in | |
| 1179 | + * between some of our reads. We try this twice before | |
| 1180 | + * resorting to traversal. | |
| 1181 | + */ | |
| 1182 | + Node h, s; | |
| 1183 | + Thread st; | |
| 1184 | + if (((h = head) != null && (s = h.next) != null && | |
| 1185 | + s.prev == head && (st = s.thread) != null) || | |
| 1186 | + ((h = head) != null && (s = h.next) != null && | |
| 1187 | + s.prev == head && (st = s.thread) != null)) | |
| 1188 | + return st; | |
| 1189 | + | |
| 1190 | + /* | |
| 1191 | + * Head's next field might not have been set yet, or may have | |
| 1192 | + * been unset after setHead. So we must check to see if tail | |
| 1193 | + * is actually first node. If not, we continue on, safely | |
| 1194 | + * traversing from tail back to head to find first, | |
| 1195 | + * guaranteeing termination. | |
| 1196 | + */ | |
| 1197 | + | |
| 1198 | + Node t = tail; | |
| 1199 | + Thread firstThread = null; | |
| 1200 | + while (t != null && t != head) { | |
| 1201 | + Thread tt = t.thread; | |
| 1202 | + if (tt != null) | |
| 1203 | + firstThread = tt; | |
| 1204 | + t = t.prev; | |
| 1205 | + } | |
| 1206 | + return firstThread; | |
| 1207 | + } | |
| 1208 | + | |
| 1209 | + /** | |
| 1210 | + * Returns true if the given thread is currently queued. | |
| 1211 | + * | |
| 1212 | + * <p>This implementation traverses the queue to determine | |
| 1213 | + * presence of the given thread. | |
| 1214 | + * | |
| 1215 | + * @param thread the thread | |
| 1216 | + * @return {@code true} if the given thread is on the queue | |
| 1217 | + * @throws NullPointerException if the thread is null | |
| 1218 | + */ | |
| 1219 | + public final boolean isQueued(Thread thread) { | |
| 1220 | + if (thread == null) | |
| 1221 | + throw new NullPointerException(); | |
| 1222 | + for (Node p = tail; p != null; p = p.prev) | |
| 1223 | + if (p.thread == thread) | |
| 1224 | + return true; | |
| 1225 | + return false; | |
| 1226 | + } | |
| 1227 | + | |
| 1228 | + /** | |
| 1229 | + * Returns {@code true} if the apparent first queued thread, if one | |
| 1230 | + * exists, is waiting in exclusive mode. If this method returns | |
| 1231 | + * {@code true}, and the current thread is attempting to acquire in | |
| 1232 | + * shared mode (that is, this method is invoked from {@link | |
| 1233 | + * #tryAcquireShared}) then it is guaranteed that the current thread | |
| 1234 | + * is not the first queued thread. Used only as a heuristic in | |
| 1235 | + * ReentrantReadWriteLock. | |
| 1236 | + */ | |
| 1237 | + final boolean apparentlyFirstQueuedIsExclusive() { | |
| 1238 | + Node h, s; | |
| 1239 | + return (h = head) != null && | |
| 1240 | + (s = h.next) != null && | |
| 1241 | + !s.isShared() && | |
| 1242 | + s.thread != null; | |
| 1243 | + } | |
| 1244 | + | |
| 1245 | + /** | |
| 1246 | + * Queries whether any threads have been waiting to acquire longer | |
| 1247 | + * than the current thread. | |
| 1248 | + * | |
| 1249 | + * <p>An invocation of this method is equivalent to (but may be | |
| 1250 | + * more efficient than): | |
| 1251 | + * <pre> {@code | |
| 1252 | + * getFirstQueuedThread() != Thread.currentThread() && | |
| 1253 | + * hasQueuedThreads()}</pre> | |
| 1254 | + * | |
| 1255 | + * <p>Note that because cancellations due to interrupts and | |
| 1256 | + * timeouts may occur at any time, a {@code true} return does not | |
| 1257 | + * guarantee that some other thread will acquire before the current | |
| 1258 | + * thread. Likewise, it is possible for another thread to win a | |
| 1259 | + * race to enqueue after this method has returned {@code false}, | |
| 1260 | + * due to the queue being empty. | |
| 1261 | + * | |
| 1262 | + * <p>This method is designed to be used by a fair synchronizer to | |
| 1263 | + * avoid <a href="AbstractQueuedSynchronizer#barging">barging</a>. | |
| 1264 | + * Such a synchronizer's {@link #tryAcquire} method should return | |
| 1265 | + * {@code false}, and its {@link #tryAcquireShared} method should | |
| 1266 | + * return a negative value, if this method returns {@code true} | |
| 1267 | + * (unless this is a reentrant acquire). For example, the {@code | |
| 1268 | + * tryAcquire} method for a fair, reentrant, exclusive mode | |
| 1269 | + * synchronizer might look like this: | |
| 1270 | + * | |
| 1271 | + * <pre> {@code | |
| 1272 | + * protected boolean tryAcquire(int arg) { | |
| 1273 | + * if (isHeldExclusively()) { | |
| 1274 | + * // A reentrant acquire; increment hold count | |
| 1275 | + * return true; | |
| 1276 | + * } else if (hasQueuedPredecessors()) { | |
| 1277 | + * return false; | |
| 1278 | + * } else { | |
| 1279 | + * // try to acquire normally | |
| 1280 | + * } | |
| 1281 | + * }}</pre> | |
| 1282 | + * | |
| 1283 | + * @return {@code true} if there is a queued thread preceding the | |
| 1284 | + * current thread, and {@code false} if the current thread | |
| 1285 | + * is at the head of the queue or the queue is empty | |
| 1286 | + * @since 1.7 | |
| 1287 | + */ | |
| 1288 | + public final boolean hasQueuedPredecessors() { | |
| 1289 | + // The correctness of this depends on head being initialized | |
| 1290 | + // before tail and on head.next being accurate if the current | |
| 1291 | + // thread is first in queue. | |
| 1292 | + Node t = tail; // Read fields in reverse initialization order | |
| 1293 | + Node h = head; | |
| 1294 | + Node s; | |
| 1295 | + return h != t && | |
| 1296 | + ((s = h.next) == null || s.thread != Thread.currentThread()); | |
| 1297 | + } | |
| 1298 | + | |
| 1299 | + | |
| 1300 | + // Instrumentation and monitoring methods | |
| 1301 | + | |
| 1302 | + /** | |
| 1303 | + * Returns an estimate of the number of threads waiting to | |
| 1304 | + * acquire. The value is only an estimate because the number of | |
| 1305 | + * threads may change dynamically while this method traverses | |
| 1306 | + * internal data structures. This method is designed for use in | |
| 1307 | + * monitoring system state, not for synchronization | |
| 1308 | + * control. | |
| 1309 | + * | |
| 1310 | + * @return the estimated number of threads waiting to acquire | |
| 1311 | + */ | |
| 1312 | + public final int getQueueLength() { | |
| 1313 | + int n = 0; | |
| 1314 | + for (Node p = tail; p != null; p = p.prev) { | |
| 1315 | + if (p.thread != null) | |
| 1316 | + ++n; | |
| 1317 | + } | |
| 1318 | + return n; | |
| 1319 | + } | |
| 1320 | + | |
| 1321 | + /** | |
| 1322 | + * Returns a collection containing threads that may be waiting to | |
| 1323 | + * acquire. Because the actual set of threads may change | |
| 1324 | + * dynamically while constructing this result, the returned | |
| 1325 | + * collection is only a best-effort estimate. The elements of the | |
| 1326 | + * returned collection are in no particular order. This method is | |
| 1327 | + * designed to facilitate construction of subclasses that provide | |
| 1328 | + * more extensive monitoring facilities. | |
| 1329 | + * | |
| 1330 | + * @return the collection of threads | |
| 1331 | + */ | |
| 1332 | + public final Collection<Thread> getQueuedThreads() { | |
| 1333 | + ArrayList<Thread> list = new ArrayList<Thread>(); | |
| 1334 | + for (Node p = tail; p != null; p = p.prev) { | |
| 1335 | + Thread t = p.thread; | |
| 1336 | + if (t != null) | |
| 1337 | + list.add(t); | |
| 1338 | + } | |
| 1339 | + return list; | |
| 1340 | + } | |
| 1341 | + | |
| 1342 | + /** | |
| 1343 | + * Returns a collection containing threads that may be waiting to | |
| 1344 | + * acquire in exclusive mode. This has the same properties | |
| 1345 | + * as {@link #getQueuedThreads} except that it only returns | |
| 1346 | + * those threads waiting due to an exclusive acquire. | |
| 1347 | + * | |
| 1348 | + * @return the collection of threads | |
| 1349 | + */ | |
| 1350 | + public final Collection<Thread> getExclusiveQueuedThreads() { | |
| 1351 | + ArrayList<Thread> list = new ArrayList<Thread>(); | |
| 1352 | + for (Node p = tail; p != null; p = p.prev) { | |
| 1353 | + if (!p.isShared()) { | |
| 1354 | + Thread t = p.thread; | |
| 1355 | + if (t != null) | |
| 1356 | + list.add(t); | |
| 1357 | + } | |
| 1358 | + } | |
| 1359 | + return list; | |
| 1360 | + } | |
| 1361 | + | |
| 1362 | + /** | |
| 1363 | + * Returns a collection containing threads that may be waiting to | |
| 1364 | + * acquire in shared mode. This has the same properties | |
| 1365 | + * as {@link #getQueuedThreads} except that it only returns | |
| 1366 | + * those threads waiting due to a shared acquire. | |
| 1367 | + * | |
| 1368 | + * @return the collection of threads | |
| 1369 | + */ | |
| 1370 | + public final Collection<Thread> getSharedQueuedThreads() { | |
| 1371 | + ArrayList<Thread> list = new ArrayList<Thread>(); | |
| 1372 | + for (Node p = tail; p != null; p = p.prev) { | |
| 1373 | + if (p.isShared()) { | |
| 1374 | + Thread t = p.thread; | |
| 1375 | + if (t != null) | |
| 1376 | + list.add(t); | |
| 1377 | + } | |
| 1378 | + } | |
| 1379 | + return list; | |
| 1380 | + } | |
| 1381 | + | |
| 1382 | + /** | |
| 1383 | + * Returns a string identifying this synchronizer, as well as its state. | |
| 1384 | + * The state, in brackets, includes the String {@code "State ="} | |
| 1385 | + * followed by the current value of {@link #getState}, and either | |
| 1386 | + * {@code "nonempty"} or {@code "empty"} depending on whether the | |
| 1387 | + * queue is empty. | |
| 1388 | + * | |
| 1389 | + * @return a string identifying this synchronizer, as well as its state | |
| 1390 | + */ | |
| 1391 | + public String toString() { | |
| 1392 | + long s = getState(); | |
| 1393 | + String q = hasQueuedThreads() ? "non" : ""; | |
| 1394 | + return super.toString() + | |
| 1395 | + "[State = " + s + ", " + q + "empty queue]"; | |
| 1396 | + } | |
| 1397 | + | |
| 1398 | + | |
| 1399 | + // Internal support methods for Conditions | |
| 1400 | + | |
| 1401 | + /** | |
| 1402 | + * Returns true if a node, always one that was initially placed on | |
| 1403 | + * a condition queue, is now waiting to reacquire on sync queue. | |
| 1404 | + * @param node the node | |
| 1405 | + * @return true if is reacquiring | |
| 1406 | + */ | |
| 1407 | + final boolean isOnSyncQueue(Node node) { | |
| 1408 | + if (node.waitStatus == Node.CONDITION || node.prev == null) | |
| 1409 | + return false; | |
| 1410 | + if (node.next != null) // If has successor, it must be on queue | |
| 1411 | + return true; | |
| 1412 | + /* | |
| 1413 | + * node.prev can be non-null, but not yet on queue because | |
| 1414 | + * the CAS to place it on queue can fail. So we have to | |
| 1415 | + * traverse from tail to make sure it actually made it. It | |
| 1416 | + * will always be near the tail in calls to this method, and | |
| 1417 | + * unless the CAS failed (which is unlikely), it will be | |
| 1418 | + * there, so we hardly ever traverse much. | |
| 1419 | + */ | |
| 1420 | + return findNodeFromTail(node); | |
| 1421 | + } | |
| 1422 | + | |
| 1423 | + /** | |
| 1424 | + * Returns true if node is on sync queue by searching backwards from tail. | |
| 1425 | + * Called only when needed by isOnSyncQueue. | |
| 1426 | + * @return true if present | |
| 1427 | + */ | |
| 1428 | + private boolean findNodeFromTail(Node node) { | |
| 1429 | + Node t = tail; | |
| 1430 | + for (;;) { | |
| 1431 | + if (t == node) | |
| 1432 | + return true; | |
| 1433 | + if (t == null) | |
| 1434 | + return false; | |
| 1435 | + t = t.prev; | |
| 1436 | + } | |
| 1437 | + } | |
| 1438 | + | |
| 1439 | + /** | |
| 1440 | + * Transfers a node from a condition queue onto sync queue. | |
| 1441 | + * Returns true if successful. | |
| 1442 | + * @param node the node | |
| 1443 | + * @return true if successfully transferred (else the node was | |
| 1444 | + * cancelled before signal). | |
| 1445 | + */ | |
| 1446 | + final boolean transferForSignal(Node node) { | |
| 1447 | + /* | |
| 1448 | + * If cannot change waitStatus, the node has been cancelled. | |
| 1449 | + */ | |
| 1450 | + if (!compareAndSetWaitStatus(node, Node.CONDITION, 0)) | |
| 1451 | + return false; | |
| 1452 | + | |
| 1453 | + /* | |
| 1454 | + * Splice onto queue and try to set waitStatus of predecessor to | |
| 1455 | + * indicate that thread is (probably) waiting. If cancelled or | |
| 1456 | + * attempt to set waitStatus fails, wake up to resync (in which | |
| 1457 | + * case the waitStatus can be transiently and harmlessly wrong). | |
| 1458 | + */ | |
| 1459 | + Node p = enq(node); | |
| 1460 | + int ws = p.waitStatus; | |
| 1461 | + if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL)) | |
| 1462 | + LockSupport.unpark(node.thread); | |
| 1463 | + return true; | |
| 1464 | + } | |
| 1465 | + | |
| 1466 | + /** | |
| 1467 | + * Transfers node, if necessary, to sync queue after a cancelled | |
| 1468 | + * wait. Returns true if thread was cancelled before being | |
| 1469 | + * signalled. | |
| 1470 | + * @param current the waiting thread | |
| 1471 | + * @param node its node | |
| 1472 | + * @return true if cancelled before the node was signalled | |
| 1473 | + */ | |
| 1474 | + final boolean transferAfterCancelledWait(Node node) { | |
| 1475 | + if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) { | |
| 1476 | + enq(node); | |
| 1477 | + return true; | |
| 1478 | + } | |
| 1479 | + /* | |
| 1480 | + * If we lost out to a signal(), then we can't proceed | |
| 1481 | + * until it finishes its enq(). Cancelling during an | |
| 1482 | + * incomplete transfer is both rare and transient, so just | |
| 1483 | + * spin. | |
| 1484 | + */ | |
| 1485 | + while (!isOnSyncQueue(node)) | |
| 1486 | + Thread.yield(); | |
| 1487 | + return false; | |
| 1488 | + } | |
| 1489 | + | |
| 1490 | + /** | |
| 1491 | + * Invokes release with current state value; returns saved state. | |
| 1492 | + * Cancels node and throws exception on failure. | |
| 1493 | + * @param node the condition node for this wait | |
| 1494 | + * @return previous sync state | |
| 1495 | + */ | |
| 1496 | + final long fullyRelease(Node node) { | |
| 1497 | + boolean failed = true; | |
| 1498 | + try { | |
| 1499 | + long savedState = getState(); | |
| 1500 | + if (release(savedState)) { | |
| 1501 | + failed = false; | |
| 1502 | + return savedState; | |
| 1503 | + } else { | |
| 1504 | + throw new IllegalMonitorStateException(); | |
| 1505 | + } | |
| 1506 | + } finally { | |
| 1507 | + if (failed) | |
| 1508 | + node.waitStatus = Node.CANCELLED; | |
| 1509 | + } | |
| 1510 | + } | |
| 1511 | + | |
| 1512 | + // Instrumentation methods for conditions | |
| 1513 | + | |
| 1514 | + /** | |
| 1515 | + * Queries whether the given ConditionObject | |
| 1516 | + * uses this synchronizer as its lock. | |
| 1517 | + * | |
| 1518 | + * @param condition the condition | |
| 1519 | + * @return <tt>true</tt> if owned | |
| 1520 | + * @throws NullPointerException if the condition is null | |
| 1521 | + */ | |
| 1522 | + public final boolean owns(ConditionObject condition) { | |
| 1523 | + if (condition == null) | |
| 1524 | + throw new NullPointerException(); | |
| 1525 | + return condition.isOwnedBy(this); | |
| 1526 | + } | |
| 1527 | + | |
| 1528 | + /** | |
| 1529 | + * Queries whether any threads are waiting on the given condition | |
| 1530 | + * associated with this synchronizer. Note that because timeouts | |
| 1531 | + * and interrupts may occur at any time, a <tt>true</tt> return | |
| 1532 | + * does not guarantee that a future <tt>signal</tt> will awaken | |
| 1533 | + * any threads. This method is designed primarily for use in | |
| 1534 | + * monitoring of the system state. | |
| 1535 | + * | |
| 1536 | + * @param condition the condition | |
| 1537 | + * @return <tt>true</tt> if there are any waiting threads | |
| 1538 | + * @throws IllegalMonitorStateException if exclusive synchronization | |
| 1539 | + * is not held | |
| 1540 | + * @throws IllegalArgumentException if the given condition is | |
| 1541 | + * not associated with this synchronizer | |
| 1542 | + * @throws NullPointerException if the condition is null | |
| 1543 | + */ | |
| 1544 | + public final boolean hasWaiters(ConditionObject condition) { | |
| 1545 | + if (!owns(condition)) | |
| 1546 | + throw new IllegalArgumentException("Not owner"); | |
| 1547 | + return condition.hasWaiters(); | |
| 1548 | + } | |
| 1549 | + | |
| 1550 | + /** | |
| 1551 | + * Returns an estimate of the number of threads waiting on the | |
| 1552 | + * given condition associated with this synchronizer. Note that | |
| 1553 | + * because timeouts and interrupts may occur at any time, the | |
| 1554 | + * estimate serves only as an upper bound on the actual number of | |
| 1555 | + * waiters. This method is designed for use in monitoring of the | |
| 1556 | + * system state, not for synchronization control. | |
| 1557 | + * | |
| 1558 | + * @param condition the condition | |
| 1559 | + * @return the estimated number of waiting threads | |
| 1560 | + * @throws IllegalMonitorStateException if exclusive synchronization | |
| 1561 | + * is not held | |
| 1562 | + * @throws IllegalArgumentException if the given condition is | |
| 1563 | + * not associated with this synchronizer | |
| 1564 | + * @throws NullPointerException if the condition is null | |
| 1565 | + */ | |
| 1566 | + public final int getWaitQueueLength(ConditionObject condition) { | |
| 1567 | + if (!owns(condition)) | |
| 1568 | + throw new IllegalArgumentException("Not owner"); | |
| 1569 | + return condition.getWaitQueueLength(); | |
| 1570 | + } | |
| 1571 | + | |
| 1572 | + /** | |
| 1573 | + * Returns a collection containing those threads that may be | |
| 1574 | + * waiting on the given condition associated with this | |
| 1575 | + * synchronizer. Because the actual set of threads may change | |
| 1576 | + * dynamically while constructing this result, the returned | |
| 1577 | + * collection is only a best-effort estimate. The elements of the | |
| 1578 | + * returned collection are in no particular order. | |
| 1579 | + * | |
| 1580 | + * @param condition the condition | |
| 1581 | + * @return the collection of threads | |
| 1582 | + * @throws IllegalMonitorStateException if exclusive synchronization | |
| 1583 | + * is not held | |
| 1584 | + * @throws IllegalArgumentException if the given condition is | |
| 1585 | + * not associated with this synchronizer | |
| 1586 | + * @throws NullPointerException if the condition is null | |
| 1587 | + */ | |
| 1588 | + public final Collection<Thread> getWaitingThreads(ConditionObject condition) { | |
| 1589 | + if (!owns(condition)) | |
| 1590 | + throw new IllegalArgumentException("Not owner"); | |
| 1591 | + return condition.getWaitingThreads(); | |
| 1592 | + } | |
| 1593 | + | |
| 1594 | + /** | |
| 1595 | + * Condition implementation for a {@link | |
| 1596 | + * AbstractQueuedLongSynchronizer} serving as the basis of a {@link | |
| 1597 | + * Lock} implementation. | |
| 1598 | + * | |
| 1599 | + * <p>Method documentation for this class describes mechanics, | |
| 1600 | + * not behavioral specifications from the point of view of Lock | |
| 1601 | + * and Condition users. Exported versions of this class will in | |
| 1602 | + * general need to be accompanied by documentation describing | |
| 1603 | + * condition semantics that rely on those of the associated | |
| 1604 | + * <tt>AbstractQueuedLongSynchronizer</tt>. | |
| 1605 | + * | |
| 1606 | + * <p>This class is Serializable, but all fields are transient, | |
| 1607 | + * so deserialized conditions have no waiters. | |
| 1608 | + * | |
| 1609 | + * @since 1.6 | |
| 1610 | + */ | |
| 1611 | + public class ConditionObject implements Condition, java.io.Serializable { | |
| 1612 | + private static final long serialVersionUID = 1173984872572414699L; | |
| 1613 | + /** First node of condition queue. */ | |
| 1614 | + private transient Node firstWaiter; | |
| 1615 | + /** Last node of condition queue. */ | |
| 1616 | + private transient Node lastWaiter; | |
| 1617 | + | |
| 1618 | + /** | |
| 1619 | + * Creates a new <tt>ConditionObject</tt> instance. | |
| 1620 | + */ | |
| 1621 | + public ConditionObject() { } | |
| 1622 | + | |
| 1623 | + // Internal methods | |
| 1624 | + | |
| 1625 | + /** | |
| 1626 | + * Adds a new waiter to wait queue. | |
| 1627 | + * @return its new wait node | |
| 1628 | + */ | |
| 1629 | + private Node addConditionWaiter() { | |
| 1630 | + Node t = lastWaiter; | |
| 1631 | + // If lastWaiter is cancelled, clean out. | |
| 1632 | + if (t != null && t.waitStatus != Node.CONDITION) { | |
| 1633 | + unlinkCancelledWaiters(); | |
| 1634 | + t = lastWaiter; | |
| 1635 | + } | |
| 1636 | + Node node = new Node(Thread.currentThread(), Node.CONDITION); | |
| 1637 | + if (t == null) | |
| 1638 | + firstWaiter = node; | |
| 1639 | + else | |
| 1640 | + t.nextWaiter = node; | |
| 1641 | + lastWaiter = node; | |
| 1642 | + return node; | |
| 1643 | + } | |
| 1644 | + | |
| 1645 | + /** | |
| 1646 | + * Removes and transfers nodes until hit non-cancelled one or | |
| 1647 | + * null. Split out from signal in part to encourage compilers | |
| 1648 | + * to inline the case of no waiters. | |
| 1649 | + * @param first (non-null) the first node on condition queue | |
| 1650 | + */ | |
| 1651 | + private void doSignal(Node first) { | |
| 1652 | + do { | |
| 1653 | + if ( (firstWaiter = first.nextWaiter) == null) | |
| 1654 | + lastWaiter = null; | |
| 1655 | + first.nextWaiter = null; | |
| 1656 | + } while (!transferForSignal(first) && | |
| 1657 | + (first = firstWaiter) != null); | |
| 1658 | + } | |
| 1659 | + | |
| 1660 | + /** | |
| 1661 | + * Removes and transfers all nodes. | |
| 1662 | + * @param first (non-null) the first node on condition queue | |
| 1663 | + */ | |
| 1664 | + private void doSignalAll(Node first) { | |
| 1665 | + lastWaiter = firstWaiter = null; | |
| 1666 | + do { | |
| 1667 | + Node next = first.nextWaiter; | |
| 1668 | + first.nextWaiter = null; | |
| 1669 | + transferForSignal(first); | |
| 1670 | + first = next; | |
| 1671 | + } while (first != null); | |
| 1672 | + } | |
| 1673 | + | |
| 1674 | + /** | |
| 1675 | + * Unlinks cancelled waiter nodes from condition queue. | |
| 1676 | + * Called only while holding lock. This is called when | |
| 1677 | + * cancellation occurred during condition wait, and upon | |
| 1678 | + * insertion of a new waiter when lastWaiter is seen to have | |
| 1679 | + * been cancelled. This method is needed to avoid garbage | |
| 1680 | + * retention in the absence of signals. So even though it may | |
| 1681 | + * require a full traversal, it comes into play only when | |
| 1682 | + * timeouts or cancellations occur in the absence of | |
| 1683 | + * signals. It traverses all nodes rather than stopping at a | |
| 1684 | + * particular target to unlink all pointers to garbage nodes | |
| 1685 | + * without requiring many re-traversals during cancellation | |
| 1686 | + * storms. | |
| 1687 | + */ | |
| 1688 | + private void unlinkCancelledWaiters() { | |
| 1689 | + Node t = firstWaiter; | |
| 1690 | + Node trail = null; | |
| 1691 | + while (t != null) { | |
| 1692 | + Node next = t.nextWaiter; | |
| 1693 | + if (t.waitStatus != Node.CONDITION) { | |
| 1694 | + t.nextWaiter = null; | |
| 1695 | + if (trail == null) | |
| 1696 | + firstWaiter = next; | |
| 1697 | + else | |
| 1698 | + trail.nextWaiter = next; | |
| 1699 | + if (next == null) | |
| 1700 | + lastWaiter = trail; | |
| 1701 | + } | |
| 1702 | + else | |
| 1703 | + trail = t; | |
| 1704 | + t = next; | |
| 1705 | + } | |
| 1706 | + } | |
| 1707 | + | |
| 1708 | + // public methods | |
| 1709 | + | |
| 1710 | + /** | |
| 1711 | + * Moves the longest-waiting thread, if one exists, from the | |
| 1712 | + * wait queue for this condition to the wait queue for the | |
| 1713 | + * owning lock. | |
| 1714 | + * | |
| 1715 | + * @throws IllegalMonitorStateException if {@link #isHeldExclusively} | |
| 1716 | + * returns {@code false} | |
| 1717 | + */ | |
| 1718 | + public final void signal() { | |
| 1719 | + if (!isHeldExclusively()) | |
| 1720 | + throw new IllegalMonitorStateException(); | |
| 1721 | + Node first = firstWaiter; | |
| 1722 | + if (first != null) | |
| 1723 | + doSignal(first); | |
| 1724 | + } | |
| 1725 | + | |
| 1726 | + /** | |
| 1727 | + * Moves all threads from the wait queue for this condition to | |
| 1728 | + * the wait queue for the owning lock. | |
| 1729 | + * | |
| 1730 | + * @throws IllegalMonitorStateException if {@link #isHeldExclusively} | |
| 1731 | + * returns {@code false} | |
| 1732 | + */ | |
| 1733 | + public final void signalAll() { | |
| 1734 | + if (!isHeldExclusively()) | |
| 1735 | + throw new IllegalMonitorStateException(); | |
| 1736 | + Node first = firstWaiter; | |
| 1737 | + if (first != null) | |
| 1738 | + doSignalAll(first); | |
| 1739 | + } | |
| 1740 | + | |
| 1741 | + /** | |
| 1742 | + * Implements uninterruptible condition wait. | |
| 1743 | + * <ol> | |
| 1744 | + * <li> Save lock state returned by {@link #getState}. | |
| 1745 | + * <li> Invoke {@link #release} with | |
| 1746 | + * saved state as argument, throwing | |
| 1747 | + * IllegalMonitorStateException if it fails. | |
| 1748 | + * <li> Block until signalled. | |
| 1749 | + * <li> Reacquire by invoking specialized version of | |
| 1750 | + * {@link #acquire} with saved state as argument. | |
| 1751 | + * </ol> | |
| 1752 | + */ | |
| 1753 | + public final void awaitUninterruptibly() { | |
| 1754 | + Node node = addConditionWaiter(); | |
| 1755 | + long savedState = fullyRelease(node); | |
| 1756 | + boolean interrupted = false; | |
| 1757 | + while (!isOnSyncQueue(node)) { | |
| 1758 | + LockSupport.park(this); | |
| 1759 | + if (Thread.interrupted()) | |
| 1760 | + interrupted = true; | |
| 1761 | + } | |
| 1762 | + if (acquireQueued(node, savedState) || interrupted) | |
| 1763 | + selfInterrupt(); | |
| 1764 | + } | |
| 1765 | + | |
| 1766 | + /* | |
| 1767 | + * For interruptible waits, we need to track whether to throw | |
| 1768 | + * InterruptedException, if interrupted while blocked on | |
| 1769 | + * condition, versus reinterrupt current thread, if | |
| 1770 | + * interrupted while blocked waiting to re-acquire. | |
| 1771 | + */ | |
| 1772 | + | |
| 1773 | + /** Mode meaning to reinterrupt on exit from wait */ | |
| 1774 | + private static final int REINTERRUPT = 1; | |
| 1775 | + /** Mode meaning to throw InterruptedException on exit from wait */ | |
| 1776 | + private static final int THROW_IE = -1; | |
| 1777 | + | |
| 1778 | + /** | |
| 1779 | + * Checks for interrupt, returning THROW_IE if interrupted | |
| 1780 | + * before signalled, REINTERRUPT if after signalled, or | |
| 1781 | + * 0 if not interrupted. | |
| 1782 | + */ | |
| 1783 | + private int checkInterruptWhileWaiting(Node node) { | |
| 1784 | + return Thread.interrupted() ? | |
| 1785 | + (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) : | |
| 1786 | + 0; | |
| 1787 | + } | |
| 1788 | + | |
| 1789 | + /** | |
| 1790 | + * Throws InterruptedException, reinterrupts current thread, or | |
| 1791 | + * does nothing, depending on mode. | |
| 1792 | + */ | |
| 1793 | + private void reportInterruptAfterWait(int interruptMode) | |
| 1794 | + throws InterruptedException { | |
| 1795 | + if (interruptMode == THROW_IE) | |
| 1796 | + throw new InterruptedException(); | |
| 1797 | + else if (interruptMode == REINTERRUPT) | |
| 1798 | + selfInterrupt(); | |
| 1799 | + } | |
| 1800 | + | |
| 1801 | + /** | |
| 1802 | + * Implements interruptible condition wait. | |
| 1803 | + * <ol> | |
| 1804 | + * <li> If current thread is interrupted, throw InterruptedException. | |
| 1805 | + * <li> Save lock state returned by {@link #getState}. | |
| 1806 | + * <li> Invoke {@link #release} with | |
| 1807 | + * saved state as argument, throwing | |
| 1808 | + * IllegalMonitorStateException if it fails. | |
| 1809 | + * <li> Block until signalled or interrupted. | |
| 1810 | + * <li> Reacquire by invoking specialized version of | |
| 1811 | + * {@link #acquire} with saved state as argument. | |
| 1812 | + * <li> If interrupted while blocked in step 4, throw InterruptedException. | |
| 1813 | + * </ol> | |
| 1814 | + */ | |
| 1815 | + public final void await() throws InterruptedException { | |
| 1816 | + if (Thread.interrupted()) | |
| 1817 | + throw new InterruptedException(); | |
| 1818 | + Node node = addConditionWaiter(); | |
| 1819 | + long savedState = fullyRelease(node); | |
| 1820 | + int interruptMode = 0; | |
| 1821 | + while (!isOnSyncQueue(node)) { | |
| 1822 | + LockSupport.park(this); | |
| 1823 | + if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) | |
| 1824 | + break; | |
| 1825 | + } | |
| 1826 | + if (acquireQueued(node, savedState) && interruptMode != THROW_IE) | |
| 1827 | + interruptMode = REINTERRUPT; | |
| 1828 | + if (node.nextWaiter != null) // clean up if cancelled | |
| 1829 | + unlinkCancelledWaiters(); | |
| 1830 | + if (interruptMode != 0) | |
| 1831 | + reportInterruptAfterWait(interruptMode); | |
| 1832 | + } | |
| 1833 | + | |
| 1834 | + /** | |
| 1835 | + * Implements timed condition wait. | |
| 1836 | + * <ol> | |
| 1837 | + * <li> If current thread is interrupted, throw InterruptedException. | |
| 1838 | + * <li> Save lock state returned by {@link #getState}. | |
| 1839 | + * <li> Invoke {@link #release} with | |
| 1840 | + * saved state as argument, throwing | |
| 1841 | + * IllegalMonitorStateException if it fails. | |
| 1842 | + * <li> Block until signalled, interrupted, or timed out. | |
| 1843 | + * <li> Reacquire by invoking specialized version of | |
| 1844 | + * {@link #acquire} with saved state as argument. | |
| 1845 | + * <li> If interrupted while blocked in step 4, throw InterruptedException. | |
| 1846 | + * </ol> | |
| 1847 | + */ | |
| 1848 | + public final long awaitNanos(long nanosTimeout) | |
| 1849 | + throws InterruptedException { | |
| 1850 | + if (Thread.interrupted()) | |
| 1851 | + throw new InterruptedException(); | |
| 1852 | + Node node = addConditionWaiter(); | |
| 1853 | + long savedState = fullyRelease(node); | |
| 1854 | + long lastTime = System.nanoTime(); | |
| 1855 | + int interruptMode = 0; | |
| 1856 | + while (!isOnSyncQueue(node)) { | |
| 1857 | + if (nanosTimeout <= 0L) { | |
| 1858 | + transferAfterCancelledWait(node); | |
| 1859 | + break; | |
| 1860 | + } | |
| 1861 | + LockSupport.parkNanos(this, nanosTimeout); | |
| 1862 | + if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) | |
| 1863 | + break; | |
| 1864 | + | |
| 1865 | + long now = System.nanoTime(); | |
| 1866 | + nanosTimeout -= now - lastTime; | |
| 1867 | + lastTime = now; | |
| 1868 | + } | |
| 1869 | + if (acquireQueued(node, savedState) && interruptMode != THROW_IE) | |
| 1870 | + interruptMode = REINTERRUPT; | |
| 1871 | + if (node.nextWaiter != null) | |
| 1872 | + unlinkCancelledWaiters(); | |
| 1873 | + if (interruptMode != 0) | |
| 1874 | + reportInterruptAfterWait(interruptMode); | |
| 1875 | + return nanosTimeout - (System.nanoTime() - lastTime); | |
| 1876 | + } | |
| 1877 | + | |
| 1878 | + /** | |
| 1879 | + * Implements absolute timed condition wait. | |
| 1880 | + * <ol> | |
| 1881 | + * <li> If current thread is interrupted, throw InterruptedException. | |
| 1882 | + * <li> Save lock state returned by {@link #getState}. | |
| 1883 | + * <li> Invoke {@link #release} with | |
| 1884 | + * saved state as argument, throwing | |
| 1885 | + * IllegalMonitorStateException if it fails. | |
| 1886 | + * <li> Block until signalled, interrupted, or timed out. | |
| 1887 | + * <li> Reacquire by invoking specialized version of | |
| 1888 | + * {@link #acquire} with saved state as argument. | |
| 1889 | + * <li> If interrupted while blocked in step 4, throw InterruptedException. | |
| 1890 | + * <li> If timed out while blocked in step 4, return false, else true. | |
| 1891 | + * </ol> | |
| 1892 | + */ | |
| 1893 | + public final boolean awaitUntil(Date deadline) | |
| 1894 | + throws InterruptedException { | |
| 1895 | + if (deadline == null) | |
| 1896 | + throw new NullPointerException(); | |
| 1897 | + long abstime = deadline.getTime(); | |
| 1898 | + if (Thread.interrupted()) | |
| 1899 | + throw new InterruptedException(); | |
| 1900 | + Node node = addConditionWaiter(); | |
| 1901 | + long savedState = fullyRelease(node); | |
| 1902 | + boolean timedout = false; | |
| 1903 | + int interruptMode = 0; | |
| 1904 | + while (!isOnSyncQueue(node)) { | |
| 1905 | + if (System.currentTimeMillis() > abstime) { | |
| 1906 | + timedout = transferAfterCancelledWait(node); | |
| 1907 | + break; | |
| 1908 | + } | |
| 1909 | + LockSupport.parkUntil(this, abstime); | |
| 1910 | + if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) | |
| 1911 | + break; | |
| 1912 | + } | |
| 1913 | + if (acquireQueued(node, savedState) && interruptMode != THROW_IE) | |
| 1914 | + interruptMode = REINTERRUPT; | |
| 1915 | + if (node.nextWaiter != null) | |
| 1916 | + unlinkCancelledWaiters(); | |
| 1917 | + if (interruptMode != 0) | |
| 1918 | + reportInterruptAfterWait(interruptMode); | |
| 1919 | + return !timedout; | |
| 1920 | + } | |
| 1921 | + | |
| 1922 | + /** | |
| 1923 | + * Implements timed condition wait. | |
| 1924 | + * <ol> | |
| 1925 | + * <li> If current thread is interrupted, throw InterruptedException. | |
| 1926 | + * <li> Save lock state returned by {@link #getState}. | |
| 1927 | + * <li> Invoke {@link #release} with | |
| 1928 | + * saved state as argument, throwing | |
| 1929 | + * IllegalMonitorStateException if it fails. | |
| 1930 | + * <li> Block until signalled, interrupted, or timed out. | |
| 1931 | + * <li> Reacquire by invoking specialized version of | |
| 1932 | + * {@link #acquire} with saved state as argument. | |
| 1933 | + * <li> If interrupted while blocked in step 4, throw InterruptedException. | |
| 1934 | + * <li> If timed out while blocked in step 4, return false, else true. | |
| 1935 | + * </ol> | |
| 1936 | + */ | |
| 1937 | + public final boolean await(long time, TimeUnit unit) | |
| 1938 | + throws InterruptedException { | |
| 1939 | + if (unit == null) | |
| 1940 | + throw new NullPointerException(); | |
| 1941 | + long nanosTimeout = unit.toNanos(time); | |
| 1942 | + if (Thread.interrupted()) | |
| 1943 | + throw new InterruptedException(); | |
| 1944 | + Node node = addConditionWaiter(); | |
| 1945 | + long savedState = fullyRelease(node); | |
| 1946 | + long lastTime = System.nanoTime(); | |
| 1947 | + boolean timedout = false; | |
| 1948 | + int interruptMode = 0; | |
| 1949 | + while (!isOnSyncQueue(node)) { | |
| 1950 | + if (nanosTimeout <= 0L) { | |
| 1951 | + timedout = transferAfterCancelledWait(node); | |
| 1952 | + break; | |
| 1953 | + } | |
| 1954 | + if (nanosTimeout >= spinForTimeoutThreshold) | |
| 1955 | + LockSupport.parkNanos(this, nanosTimeout); | |
| 1956 | + if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) | |
| 1957 | + break; | |
| 1958 | + long now = System.nanoTime(); | |
| 1959 | + nanosTimeout -= now - lastTime; | |
| 1960 | + lastTime = now; | |
| 1961 | + } | |
| 1962 | + if (acquireQueued(node, savedState) && interruptMode != THROW_IE) | |
| 1963 | + interruptMode = REINTERRUPT; | |
| 1964 | + if (node.nextWaiter != null) | |
| 1965 | + unlinkCancelledWaiters(); | |
| 1966 | + if (interruptMode != 0) | |
| 1967 | + reportInterruptAfterWait(interruptMode); | |
| 1968 | + return !timedout; | |
| 1969 | + } | |
| 1970 | + | |
| 1971 | + // support for instrumentation | |
| 1972 | + | |
| 1973 | + /** | |
| 1974 | + * Returns true if this condition was created by the given | |
| 1975 | + * synchronization object. | |
| 1976 | + * | |
| 1977 | + * @return {@code true} if owned | |
| 1978 | + */ | |
| 1979 | + final boolean isOwnedBy(AbstractQueuedLongSynchronizer sync) { | |
| 1980 | + return sync == AbstractQueuedLongSynchronizer.this; | |
| 1981 | + } | |
| 1982 | + | |
| 1983 | + /** | |
| 1984 | + * Queries whether any threads are waiting on this condition. | |
| 1985 | + * Implements {@link AbstractQueuedLongSynchronizer#hasWaiters}. | |
| 1986 | + * | |
| 1987 | + * @return {@code true} if there are any waiting threads | |
| 1988 | + * @throws IllegalMonitorStateException if {@link #isHeldExclusively} | |
| 1989 | + * returns {@code false} | |
| 1990 | + */ | |
| 1991 | + protected final boolean hasWaiters() { | |
| 1992 | + if (!isHeldExclusively()) | |
| 1993 | + throw new IllegalMonitorStateException(); | |
| 1994 | + for (Node w = firstWaiter; w != null; w = w.nextWaiter) { | |
| 1995 | + if (w.waitStatus == Node.CONDITION) | |
| 1996 | + return true; | |
| 1997 | + } | |
| 1998 | + return false; | |
| 1999 | + } | |
| 2000 | + | |
| 2001 | + /** | |
| 2002 | + * Returns an estimate of the number of threads waiting on | |
| 2003 | + * this condition. | |
| 2004 | + * Implements {@link AbstractQueuedLongSynchronizer#getWaitQueueLength}. | |
| 2005 | + * | |
| 2006 | + * @return the estimated number of waiting threads | |
| 2007 | + * @throws IllegalMonitorStateException if {@link #isHeldExclusively} | |
| 2008 | + * returns {@code false} | |
| 2009 | + */ | |
| 2010 | + protected final int getWaitQueueLength() { | |
| 2011 | + if (!isHeldExclusively()) | |
| 2012 | + throw new IllegalMonitorStateException(); | |
| 2013 | + int n = 0; | |
| 2014 | + for (Node w = firstWaiter; w != null; w = w.nextWaiter) { | |
| 2015 | + if (w.waitStatus == Node.CONDITION) | |
| 2016 | + ++n; | |
| 2017 | + } | |
| 2018 | + return n; | |
| 2019 | + } | |
| 2020 | + | |
| 2021 | + /** | |
| 2022 | + * Returns a collection containing those threads that may be | |
| 2023 | + * waiting on this Condition. | |
| 2024 | + * Implements {@link AbstractQueuedLongSynchronizer#getWaitingThreads}. | |
| 2025 | + * | |
| 2026 | + * @return the collection of threads | |
| 2027 | + * @throws IllegalMonitorStateException if {@link #isHeldExclusively} | |
| 2028 | + * returns {@code false} | |
| 2029 | + */ | |
| 2030 | + protected final Collection<Thread> getWaitingThreads() { | |
| 2031 | + if (!isHeldExclusively()) | |
| 2032 | + throw new IllegalMonitorStateException(); | |
| 2033 | + ArrayList<Thread> list = new ArrayList<Thread>(); | |
| 2034 | + for (Node w = firstWaiter; w != null; w = w.nextWaiter) { | |
| 2035 | + if (w.waitStatus == Node.CONDITION) { | |
| 2036 | + Thread t = w.thread; | |
| 2037 | + if (t != null) | |
| 2038 | + list.add(t); | |
| 2039 | + } | |
| 2040 | + } | |
| 2041 | + return list; | |
| 2042 | + } | |
| 2043 | + } | |
| 2044 | + | |
| 2045 | + /** | |
| 2046 | + * Setup to support compareAndSet. We need to natively implement | |
| 2047 | + * this here: For the sake of permitting future enhancements, we | |
| 2048 | + * cannot explicitly subclass AtomicLong, which would be | |
| 2049 | + * efficient and useful otherwise. So, as the lesser of evils, we | |
| 2050 | + * natively implement using hotspot intrinsics API. And while we | |
| 2051 | + * are at it, we do the same for other CASable fields (which could | |
| 2052 | + * otherwise be done with atomic field updaters). | |
| 2053 | + */ | |
| 2054 | + private static final Unsafe unsafe = Unsafe.getUnsafe(); | |
| 2055 | + private static final long stateOffset; | |
| 2056 | + private static final long headOffset; | |
| 2057 | + private static final long tailOffset; | |
| 2058 | + private static final long waitStatusOffset; | |
| 2059 | + private static final long nextOffset; | |
| 2060 | + | |
| 2061 | + static { | |
| 2062 | + try { | |
| 2063 | + stateOffset = unsafe.objectFieldOffset | |
| 2064 | + (AbstractQueuedLongSynchronizer.class.getDeclaredField("state")); | |
| 2065 | + headOffset = unsafe.objectFieldOffset | |
| 2066 | + (AbstractQueuedLongSynchronizer.class.getDeclaredField("head")); | |
| 2067 | + tailOffset = unsafe.objectFieldOffset | |
| 2068 | + (AbstractQueuedLongSynchronizer.class.getDeclaredField("tail")); | |
| 2069 | + waitStatusOffset = unsafe.objectFieldOffset | |
| 2070 | + (Node.class.getDeclaredField("waitStatus")); | |
| 2071 | + nextOffset = unsafe.objectFieldOffset | |
| 2072 | + (Node.class.getDeclaredField("next")); | |
| 2073 | + | |
| 2074 | + } catch (Exception ex) { throw new Error(ex); } | |
| 2075 | + } | |
| 2076 | + | |
| 2077 | + /** | |
| 2078 | + * CAS head field. Used only by enq. | |
| 2079 | + */ | |
| 2080 | + private final boolean compareAndSetHead(Node update) { | |
| 2081 | + return unsafe.compareAndSwapObject(this, headOffset, null, update); | |
| 2082 | + } | |
| 2083 | + | |
| 2084 | + /** | |
| 2085 | + * CAS tail field. Used only by enq. | |
| 2086 | + */ | |
| 2087 | + private final boolean compareAndSetTail(Node expect, Node update) { | |
| 2088 | + return unsafe.compareAndSwapObject(this, tailOffset, expect, update); | |
| 2089 | + } | |
| 2090 | + | |
| 2091 | + /** | |
| 2092 | + * CAS waitStatus field of a node. | |
| 2093 | + */ | |
| 2094 | + private static final boolean compareAndSetWaitStatus(Node node, | |
| 2095 | + int expect, | |
| 2096 | + int update) { | |
| 2097 | + return unsafe.compareAndSwapInt(node, waitStatusOffset, | |
| 2098 | + expect, update); | |
| 2099 | + } | |
| 2100 | + | |
| 2101 | + /** | |
| 2102 | + * CAS next field of a node. | |
| 2103 | + */ | |
| 2104 | + private static final boolean compareAndSetNext(Node node, | |
| 2105 | + Node expect, | |
| 2106 | + Node update) { | |
| 2107 | + return unsafe.compareAndSwapObject(node, nextOffset, expect, update); | |
| 2108 | + } | |
| 2109 | +} | |
Binary file not shown.
Binary file not shown.
Binary file not shown.
| @@ -0,0 +1,2330 @@ | ||
| 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 | +import java.util.*; | |
| 38 | +import java.util.concurrent.*; | |
| 39 | +import java.util.concurrent.atomic.*; | |
| 40 | +import sun.misc.Unsafe; | |
| 41 | + | |
| 42 | +/** | |
| 43 | + * Provides a framework for implementing blocking locks and related | |
| 44 | + * synchronizers (semaphores, events, etc) that rely on | |
| 45 | + * first-in-first-out (FIFO) wait queues. This class is designed to | |
| 46 | + * be a useful basis for most kinds of synchronizers that rely on a | |
| 47 | + * single atomic <tt>int</tt> value to represent state. Subclasses | |
| 48 | + * must define the protected methods that change this state, and which | |
| 49 | + * define what that state means in terms of this object being acquired | |
| 50 | + * or released. Given these, the other methods in this class carry | |
| 51 | + * out all queuing and blocking mechanics. Subclasses can maintain | |
| 52 | + * other state fields, but only the atomically updated <tt>int</tt> | |
| 53 | + * value manipulated using methods {@link #getState}, {@link | |
| 54 | + * #setState} and {@link #compareAndSetState} is tracked with respect | |
| 55 | + * to synchronization. | |
| 56 | + * | |
| 57 | + * <p>Subclasses should be defined as non-public internal helper | |
| 58 | + * classes that are used to implement the synchronization properties | |
| 59 | + * of their enclosing class. Class | |
| 60 | + * <tt>AbstractQueuedSynchronizer</tt> does not implement any | |
| 61 | + * synchronization interface. Instead it defines methods such as | |
| 62 | + * {@link #acquireInterruptibly} that can be invoked as | |
| 63 | + * appropriate by concrete locks and related synchronizers to | |
| 64 | + * implement their public methods. | |
| 65 | + * | |
| 66 | + * <p>This class supports either or both a default <em>exclusive</em> | |
| 67 | + * mode and a <em>shared</em> mode. When acquired in exclusive mode, | |
| 68 | + * attempted acquires by other threads cannot succeed. Shared mode | |
| 69 | + * acquires by multiple threads may (but need not) succeed. This class | |
| 70 | + * does not "understand" these differences except in the | |
| 71 | + * mechanical sense that when a shared mode acquire succeeds, the next | |
| 72 | + * waiting thread (if one exists) must also determine whether it can | |
| 73 | + * acquire as well. Threads waiting in the different modes share the | |
| 74 | + * same FIFO queue. Usually, implementation subclasses support only | |
| 75 | + * one of these modes, but both can come into play for example in a | |
| 76 | + * {@link ReadWriteLock}. Subclasses that support only exclusive or | |
| 77 | + * only shared modes need not define the methods supporting the unused mode. | |
| 78 | + * | |
| 79 | + * <p>This class defines a nested {@link ConditionObject} class that | |
| 80 | + * can be used as a {@link Condition} implementation by subclasses | |
| 81 | + * supporting exclusive mode for which method {@link | |
| 82 | + * #isHeldExclusively} reports whether synchronization is exclusively | |
| 83 | + * held with respect to the current thread, method {@link #release} | |
| 84 | + * invoked with the current {@link #getState} value fully releases | |
| 85 | + * this object, and {@link #acquire}, given this saved state value, | |
| 86 | + * eventually restores this object to its previous acquired state. No | |
| 87 | + * <tt>AbstractQueuedSynchronizer</tt> method otherwise creates such a | |
| 88 | + * condition, so if this constraint cannot be met, do not use it. The | |
| 89 | + * behavior of {@link ConditionObject} depends of course on the | |
| 90 | + * semantics of its synchronizer implementation. | |
| 91 | + * | |
| 92 | + * <p>This class provides inspection, instrumentation, and monitoring | |
| 93 | + * methods for the internal queue, as well as similar methods for | |
| 94 | + * condition objects. These can be exported as desired into classes | |
| 95 | + * using an <tt>AbstractQueuedSynchronizer</tt> for their | |
| 96 | + * synchronization mechanics. | |
| 97 | + * | |
| 98 | + * <p>Serialization of this class stores only the underlying atomic | |
| 99 | + * integer maintaining state, so deserialized objects have empty | |
| 100 | + * thread queues. Typical subclasses requiring serializability will | |
| 101 | + * define a <tt>readObject</tt> method that restores this to a known | |
| 102 | + * initial state upon deserialization. | |
| 103 | + * | |
| 104 | + * <h3>Usage</h3> | |
| 105 | + * | |
| 106 | + * <p>To use this class as the basis of a synchronizer, redefine the | |
| 107 | + * following methods, as applicable, by inspecting and/or modifying | |
| 108 | + * the synchronization state using {@link #getState}, {@link | |
| 109 | + * #setState} and/or {@link #compareAndSetState}: | |
| 110 | + * | |
| 111 | + * <ul> | |
| 112 | + * <li> {@link #tryAcquire} | |
| 113 | + * <li> {@link #tryRelease} | |
| 114 | + * <li> {@link #tryAcquireShared} | |
| 115 | + * <li> {@link #tryReleaseShared} | |
| 116 | + * <li> {@link #isHeldExclusively} | |
| 117 | + *</ul> | |
| 118 | + * | |
| 119 | + * Each of these methods by default throws {@link | |
| 120 | + * UnsupportedOperationException}. Implementations of these methods | |
| 121 | + * must be internally thread-safe, and should in general be short and | |
| 122 | + * not block. Defining these methods is the <em>only</em> supported | |
| 123 | + * means of using this class. All other methods are declared | |
| 124 | + * <tt>final</tt> because they cannot be independently varied. | |
| 125 | + * | |
| 126 | + * <p>You may also find the inherited methods from {@link | |
| 127 | + * AbstractOwnableSynchronizer} useful to keep track of the thread | |
| 128 | + * owning an exclusive synchronizer. You are encouraged to use them | |
| 129 | + * -- this enables monitoring and diagnostic tools to assist users in | |
| 130 | + * determining which threads hold locks. | |
| 131 | + * | |
| 132 | + * <p>Even though this class is based on an internal FIFO queue, it | |
| 133 | + * does not automatically enforce FIFO acquisition policies. The core | |
| 134 | + * of exclusive synchronization takes the form: | |
| 135 | + * | |
| 136 | + * <pre> | |
| 137 | + * Acquire: | |
| 138 | + * while (!tryAcquire(arg)) { | |
| 139 | + * <em>enqueue thread if it is not already queued</em>; | |
| 140 | + * <em>possibly block current thread</em>; | |
| 141 | + * } | |
| 142 | + * | |
| 143 | + * Release: | |
| 144 | + * if (tryRelease(arg)) | |
| 145 | + * <em>unblock the first queued thread</em>; | |
| 146 | + * </pre> | |
| 147 | + * | |
| 148 | + * (Shared mode is similar but may involve cascading signals.) | |
| 149 | + * | |
| 150 | + * <p><a name="barging">Because checks in acquire are invoked before | |
| 151 | + * enqueuing, a newly acquiring thread may <em>barge</em> ahead of | |
| 152 | + * others that are blocked and queued. However, you can, if desired, | |
| 153 | + * define <tt>tryAcquire</tt> and/or <tt>tryAcquireShared</tt> to | |
| 154 | + * disable barging by internally invoking one or more of the inspection | |
| 155 | + * methods, thereby providing a <em>fair</em> FIFO acquisition order. | |
| 156 | + * In particular, most fair synchronizers can define <tt>tryAcquire</tt> | |
| 157 | + * to return <tt>false</tt> if {@link #hasQueuedPredecessors} (a method | |
| 158 | + * specifically designed to be used by fair synchronizers) returns | |
| 159 | + * <tt>true</tt>. Other variations are possible. | |
| 160 | + * | |
| 161 | + * <p>Throughput and scalability are generally highest for the | |
| 162 | + * default barging (also known as <em>greedy</em>, | |
| 163 | + * <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy. | |
| 164 | + * While this is not guaranteed to be fair or starvation-free, earlier | |
| 165 | + * queued threads are allowed to recontend before later queued | |
| 166 | + * threads, and each recontention has an unbiased chance to succeed | |
| 167 | + * against incoming threads. Also, while acquires do not | |
| 168 | + * "spin" in the usual sense, they may perform multiple | |
| 169 | + * invocations of <tt>tryAcquire</tt> interspersed with other | |
| 170 | + * computations before blocking. This gives most of the benefits of | |
| 171 | + * spins when exclusive synchronization is only briefly held, without | |
| 172 | + * most of the liabilities when it isn't. If so desired, you can | |
| 173 | + * augment this by preceding calls to acquire methods with | |
| 174 | + * "fast-path" checks, possibly prechecking {@link #hasContended} | |
| 175 | + * and/or {@link #hasQueuedThreads} to only do so if the synchronizer | |
| 176 | + * is likely not to be contended. | |
| 177 | + * | |
| 178 | + * <p>This class provides an efficient and scalable basis for | |
| 179 | + * synchronization in part by specializing its range of use to | |
| 180 | + * synchronizers that can rely on <tt>int</tt> state, acquire, and | |
| 181 | + * release parameters, and an internal FIFO wait queue. When this does | |
| 182 | + * not suffice, you can build synchronizers from a lower level using | |
| 183 | + * {@link java.util.concurrent.atomic atomic} classes, your own custom | |
| 184 | + * {@link java.util.Queue} classes, and {@link LockSupport} blocking | |
| 185 | + * support. | |
| 186 | + * | |
| 187 | + * <h3>Usage Examples</h3> | |
| 188 | + * | |
| 189 | + * <p>Here is a non-reentrant mutual exclusion lock class that uses | |
| 190 | + * the value zero to represent the unlocked state, and one to | |
| 191 | + * represent the locked state. While a non-reentrant lock | |
| 192 | + * does not strictly require recording of the current owner | |
| 193 | + * thread, this class does so anyway to make usage easier to monitor. | |
| 194 | + * It also supports conditions and exposes | |
| 195 | + * one of the instrumentation methods: | |
| 196 | + * | |
| 197 | + * <pre> | |
| 198 | + * class Mutex implements Lock, java.io.Serializable { | |
| 199 | + * | |
| 200 | + * // Our internal helper class | |
| 201 | + * private static class Sync extends AbstractQueuedSynchronizer { | |
| 202 | + * // Report whether in locked state | |
| 203 | + * protected boolean isHeldExclusively() { | |
| 204 | + * return getState() == 1; | |
| 205 | + * } | |
| 206 | + * | |
| 207 | + * // Acquire the lock if state is zero | |
| 208 | + * public boolean tryAcquire(int acquires) { | |
| 209 | + * assert acquires == 1; // Otherwise unused | |
| 210 | + * if (compareAndSetState(0, 1)) { | |
| 211 | + * setExclusiveOwnerThread(Thread.currentThread()); | |
| 212 | + * return true; | |
| 213 | + * } | |
| 214 | + * return false; | |
| 215 | + * } | |
| 216 | + * | |
| 217 | + * // Release the lock by setting state to zero | |
| 218 | + * protected boolean tryRelease(int releases) { | |
| 219 | + * assert releases == 1; // Otherwise unused | |
| 220 | + * if (getState() == 0) throw new IllegalMonitorStateException(); | |
| 221 | + * setExclusiveOwnerThread(null); | |
| 222 | + * setState(0); | |
| 223 | + * return true; | |
| 224 | + * } | |
| 225 | + * | |
| 226 | + * // Provide a Condition | |
| 227 | + * Condition newCondition() { return new ConditionObject(); } | |
| 228 | + * | |
| 229 | + * // Deserialize properly | |
| 230 | + * private void readObject(ObjectInputStream s) | |
| 231 | + * throws IOException, ClassNotFoundException { | |
| 232 | + * s.defaultReadObject(); | |
| 233 | + * setState(0); // reset to unlocked state | |
| 234 | + * } | |
| 235 | + * } | |
| 236 | + * | |
| 237 | + * // The sync object does all the hard work. We just forward to it. | |
| 238 | + * private final Sync sync = new Sync(); | |
| 239 | + * | |
| 240 | + * public void lock() { sync.acquire(1); } | |
| 241 | + * public boolean tryLock() { return sync.tryAcquire(1); } | |
| 242 | + * public void unlock() { sync.release(1); } | |
| 243 | + * public Condition newCondition() { return sync.newCondition(); } | |
| 244 | + * public boolean isLocked() { return sync.isHeldExclusively(); } | |
| 245 | + * public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } | |
| 246 | + * public void lockInterruptibly() throws InterruptedException { | |
| 247 | + * sync.acquireInterruptibly(1); | |
| 248 | + * } | |
| 249 | + * public boolean tryLock(long timeout, TimeUnit unit) | |
| 250 | + * throws InterruptedException { | |
| 251 | + * return sync.tryAcquireNanos(1, unit.toNanos(timeout)); | |
| 252 | + * } | |
| 253 | + * } | |
| 254 | + * </pre> | |
| 255 | + * | |
| 256 | + * <p>Here is a latch class that is like a {@link CountDownLatch} | |
| 257 | + * except that it only requires a single <tt>signal</tt> to | |
| 258 | + * fire. Because a latch is non-exclusive, it uses the <tt>shared</tt> | |
| 259 | + * acquire and release methods. | |
| 260 | + * | |
| 261 | + * <pre> | |
| 262 | + * class BooleanLatch { | |
| 263 | + * | |
| 264 | + * private static class Sync extends AbstractQueuedSynchronizer { | |
| 265 | + * boolean isSignalled() { return getState() != 0; } | |
| 266 | + * | |
| 267 | + * protected int tryAcquireShared(int ignore) { | |
| 268 | + * return isSignalled() ? 1 : -1; | |
| 269 | + * } | |
| 270 | + * | |
| 271 | + * protected boolean tryReleaseShared(int ignore) { | |
| 272 | + * setState(1); | |
| 273 | + * return true; | |
| 274 | + * } | |
| 275 | + * } | |
| 276 | + * | |
| 277 | + * private final Sync sync = new Sync(); | |
| 278 | + * public boolean isSignalled() { return sync.isSignalled(); } | |
| 279 | + * public void signal() { sync.releaseShared(1); } | |
| 280 | + * public void await() throws InterruptedException { | |
| 281 | + * sync.acquireSharedInterruptibly(1); | |
| 282 | + * } | |
| 283 | + * } | |
| 284 | + * </pre> | |
| 285 | + * | |
| 286 | + * @since 1.5 | |
| 287 | + * @author Doug Lea | |
| 288 | + */ | |
| 289 | +public abstract class AbstractQueuedSynchronizer | |
| 290 | + extends AbstractOwnableSynchronizer | |
| 291 | + implements java.io.Serializable { | |
| 292 | + | |
| 293 | + private static final long serialVersionUID = 7373984972572414691L; | |
| 294 | + | |
| 295 | + /** | |
| 296 | + * Creates a new <tt>AbstractQueuedSynchronizer</tt> instance | |
| 297 | + * with initial synchronization state of zero. | |
| 298 | + */ | |
| 299 | + protected AbstractQueuedSynchronizer() { } | |
| 300 | + | |
| 301 | + /** | |
| 302 | + * Wait queue node class. | |
| 303 | + * | |
| 304 | + * <p>The wait queue is a variant of a "CLH" (Craig, Landin, and | |
| 305 | + * Hagersten) lock queue. CLH locks are normally used for | |
| 306 | + * spinlocks. We instead use them for blocking synchronizers, but | |
| 307 | + * use the same basic tactic of holding some of the control | |
| 308 | + * information about a thread in the predecessor of its node. A | |
| 309 | + * "status" field in each node keeps track of whether a thread | |
| 310 | + * should block. A node is signalled when its predecessor | |
| 311 | + * releases. Each node of the queue otherwise serves as a | |
| 312 | + * specific-notification-style monitor holding a single waiting | |
| 313 | + * thread. The status field does NOT control whether threads are | |
| 314 | + * granted locks etc though. A thread may try to acquire if it is | |
| 315 | + * first in the queue. But being first does not guarantee success; | |
| 316 | + * it only gives the right to contend. So the currently released | |
| 317 | + * contender thread may need to rewait. | |
| 318 | + * | |
| 319 | + * <p>To enqueue into a CLH lock, you atomically splice it in as new | |
| 320 | + * tail. To dequeue, you just set the head field. | |
| 321 | + * <pre> | |
| 322 | + * +------+ prev +-----+ +-----+ | |
| 323 | + * head | | <---- | | <---- | | tail | |
| 324 | + * +------+ +-----+ +-----+ | |
| 325 | + * </pre> | |
| 326 | + * | |
| 327 | + * <p>Insertion into a CLH queue requires only a single atomic | |
| 328 | + * operation on "tail", so there is a simple atomic point of | |
| 329 | + * demarcation from unqueued to queued. Similarly, dequeing | |
| 330 | + * involves only updating the "head". However, it takes a bit | |
| 331 | + * more work for nodes to determine who their successors are, | |
| 332 | + * in part to deal with possible cancellation due to timeouts | |
| 333 | + * and interrupts. | |
| 334 | + * | |
| 335 | + * <p>The "prev" links (not used in original CLH locks), are mainly | |
| 336 | + * needed to handle cancellation. If a node is cancelled, its | |
| 337 | + * successor is (normally) relinked to a non-cancelled | |
| 338 | + * predecessor. For explanation of similar mechanics in the case | |
| 339 | + * of spin locks, see the papers by Scott and Scherer at | |
| 340 | + * http://www.cs.rochester.edu/u/scott/synchronization/ | |
| 341 | + * | |
| 342 | + * <p>We also use "next" links to implement blocking mechanics. | |
| 343 | + * The thread id for each node is kept in its own node, so a | |
| 344 | + * predecessor signals the next node to wake up by traversing | |
| 345 | + * next link to determine which thread it is. Determination of | |
| 346 | + * successor must avoid races with newly queued nodes to set | |
| 347 | + * the "next" fields of their predecessors. This is solved | |
| 348 | + * when necessary by checking backwards from the atomically | |
| 349 | + * updated "tail" when a node's successor appears to be null. | |
| 350 | + * (Or, said differently, the next-links are an optimization | |
| 351 | + * so that we don't usually need a backward scan.) | |
| 352 | + * | |
| 353 | + * <p>Cancellation introduces some conservatism to the basic | |
| 354 | + * algorithms. Since we must poll for cancellation of other | |
| 355 | + * nodes, we can miss noticing whether a cancelled node is | |
| 356 | + * ahead or behind us. This is dealt with by always unparking | |
| 357 | + * successors upon cancellation, allowing them to stabilize on | |
| 358 | + * a new predecessor, unless we can identify an uncancelled | |
| 359 | + * predecessor who will carry this responsibility. | |
| 360 | + * | |
| 361 | + * <p>CLH queues need a dummy header node to get started. But | |
| 362 | + * we don't create them on construction, because it would be wasted | |
| 363 | + * effort if there is never contention. Instead, the node | |
| 364 | + * is constructed and head and tail pointers are set upon first | |
| 365 | + * contention. | |
| 366 | + * | |
| 367 | + * <p>Threads waiting on Conditions use the same nodes, but | |
| 368 | + * use an additional link. Conditions only need to link nodes | |
| 369 | + * in simple (non-concurrent) linked queues because they are | |
| 370 | + * only accessed when exclusively held. Upon await, a node is | |
| 371 | + * inserted into a condition queue. Upon signal, the node is | |
| 372 | + * transferred to the main queue. A special value of status | |
| 373 | + * field is used to mark which queue a node is on. | |
| 374 | + * | |
| 375 | + * <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill | |
| 376 | + * Scherer and Michael Scott, along with members of JSR-166 | |
| 377 | + * expert group, for helpful ideas, discussions, and critiques | |
| 378 | + * on the design of this class. | |
| 379 | + */ | |
| 380 | + static final class Node { | |
| 381 | + /** Marker to indicate a node is waiting in shared mode */ | |
| 382 | + static final Node SHARED = new Node(); | |
| 383 | + /** Marker to indicate a node is waiting in exclusive mode */ | |
| 384 | + static final Node EXCLUSIVE = null; | |
| 385 | + | |
| 386 | + /** waitStatus value to indicate thread has cancelled */ | |
| 387 | + static final int CANCELLED = 1; | |
| 388 | + /** waitStatus value to indicate successor's thread needs unparking */ | |
| 389 | + static final int SIGNAL = -1; | |
| 390 | + /** waitStatus value to indicate thread is waiting on condition */ | |
| 391 | + static final int CONDITION = -2; | |
| 392 | + /** | |
| 393 | + * waitStatus value to indicate the next acquireShared should | |
| 394 | + * unconditionally propagate | |
| 395 | + */ | |
| 396 | + static final int PROPAGATE = -3; | |
| 397 | + | |
| 398 | + /** | |
| 399 | + * Status field, taking on only the values: | |
| 400 | + * SIGNAL: The successor of this node is (or will soon be) | |
| 401 | + * blocked (via park), so the current node must | |
| 402 | + * unpark its successor when it releases or | |
| 403 | + * cancels. To avoid races, acquire methods must | |
| 404 | + * first indicate they need a signal, | |
| 405 | + * then retry the atomic acquire, and then, | |
| 406 | + * on failure, block. | |
| 407 | + * CANCELLED: This node is cancelled due to timeout or interrupt. | |
| 408 | + * Nodes never leave this state. In particular, | |
| 409 | + * a thread with cancelled node never again blocks. | |
| 410 | + * CONDITION: This node is currently on a condition queue. | |
| 411 | + * It will not be used as a sync queue node | |
| 412 | + * until transferred, at which time the status | |
| 413 | + * will be set to 0. (Use of this value here has | |
| 414 | + * nothing to do with the other uses of the | |
| 415 | + * field, but simplifies mechanics.) | |
| 416 | + * PROPAGATE: A releaseShared should be propagated to other | |
| 417 | + * nodes. This is set (for head node only) in | |
| 418 | + * doReleaseShared to ensure propagation | |
| 419 | + * continues, even if other operations have | |
| 420 | + * since intervened. | |
| 421 | + * 0: None of the above | |
| 422 | + * | |
| 423 | + * The values are arranged numerically to simplify use. | |
| 424 | + * Non-negative values mean that a node doesn't need to | |
| 425 | + * signal. So, most code doesn't need to check for particular | |
| 426 | + * values, just for sign. | |
| 427 | + * | |
| 428 | + * The field is initialized to 0 for normal sync nodes, and | |
| 429 | + * CONDITION for condition nodes. It is modified using CAS | |
| 430 | + * (or when possible, unconditional volatile writes). | |
| 431 | + */ | |
| 432 | + volatile int waitStatus; | |
| 433 | + | |
| 434 | + /** | |
| 435 | + * Link to predecessor node that current node/thread relies on | |
| 436 | + * for checking waitStatus. Assigned during enqueing, and nulled | |
| 437 | + * out (for sake of GC) only upon dequeuing. Also, upon | |
| 438 | + * cancellation of a predecessor, we short-circuit while | |
| 439 | + * finding a non-cancelled one, which will always exist | |
| 440 | + * because the head node is never cancelled: A node becomes | |
| 441 | + * head only as a result of successful acquire. A | |
| 442 | + * cancelled thread never succeeds in acquiring, and a thread only | |
| 443 | + * cancels itself, not any other node. | |
| 444 | + */ | |
| 445 | + volatile Node prev; | |
| 446 | + | |
| 447 | + /** | |
| 448 | + * Link to the successor node that the current node/thread | |
| 449 | + * unparks upon release. Assigned during enqueuing, adjusted | |
| 450 | + * when bypassing cancelled predecessors, and nulled out (for | |
| 451 | + * sake of GC) when dequeued. The enq operation does not | |
| 452 | + * assign next field of a predecessor until after attachment, | |
| 453 | + * so seeing a null next field does not necessarily mean that | |
| 454 | + * node is at end of queue. However, if a next field appears | |
| 455 | + * to be null, we can scan prev's from the tail to | |
| 456 | + * double-check. The next field of cancelled nodes is set to | |
| 457 | + * point to the node itself instead of null, to make life | |
| 458 | + * easier for isOnSyncQueue. | |
| 459 | + */ | |
| 460 | + volatile Node next; | |
| 461 | + | |
| 462 | + /** | |
| 463 | + * The thread that enqueued this node. Initialized on | |
| 464 | + * construction and nulled out after use. | |
| 465 | + */ | |
| 466 | + volatile Thread thread; | |
| 467 | + | |
| 468 | + /** | |
| 469 | + * Link to next node waiting on condition, or the special | |
| 470 | + * value SHARED. Because condition queues are accessed only | |
| 471 | + * when holding in exclusive mode, we just need a simple | |
| 472 | + * linked queue to hold nodes while they are waiting on | |
| 473 | + * conditions. They are then transferred to the queue to | |
| 474 | + * re-acquire. And because conditions can only be exclusive, | |
| 475 | + * we save a field by using special value to indicate shared | |
| 476 | + * mode. | |
| 477 | + */ | |
| 478 | + Node nextWaiter; | |
| 479 | + | |
| 480 | + /** | |
| 481 | + * Returns true if node is waiting in shared mode | |
| 482 | + */ | |
| 483 | + final boolean isShared() { | |
| 484 | + return nextWaiter == SHARED; | |
| 485 | + } | |
| 486 | + | |
| 487 | + /** | |
| 488 | + * Returns previous node, or throws NullPointerException if null. | |
| 489 | + * Use when predecessor cannot be null. The null check could | |
| 490 | + * be elided, but is present to help the VM. | |
| 491 | + * | |
| 492 | + * @return the predecessor of this node | |
| 493 | + */ | |
| 494 | + final Node predecessor() throws NullPointerException { | |
| 495 | + Node p = prev; | |
| 496 | + if (p == null) | |
| 497 | + throw new NullPointerException(); | |
| 498 | + else | |
| 499 | + return p; | |
| 500 | + } | |
| 501 | + | |
| 502 | + Node() { // Used to establish initial head or SHARED marker | |
| 503 | + } | |
| 504 | + | |
| 505 | + Node(Thread thread, Node mode) { // Used by addWaiter | |
| 506 | + this.nextWaiter = mode; | |
| 507 | + this.thread = thread; | |
| 508 | + } | |
| 509 | + | |
| 510 | + Node(Thread thread, int waitStatus) { // Used by Condition | |
| 511 | + this.waitStatus = waitStatus; | |
| 512 | + this.thread = thread; | |
| 513 | + } | |
| 514 | + } | |
| 515 | + | |
| 516 | + /** | |
| 517 | + * Head of the wait queue, lazily initialized. Except for | |
| 518 | + * initialization, it is modified only via method setHead. Note: | |
| 519 | + * If head exists, its waitStatus is guaranteed not to be | |
| 520 | + * CANCELLED. | |
| 521 | + */ | |
| 522 | + private transient volatile Node head; | |
| 523 | + | |
| 524 | + /** | |
| 525 | + * Tail of the wait queue, lazily initialized. Modified only via | |
| 526 | + * method enq to add new wait node. | |
| 527 | + */ | |
| 528 | + private transient volatile Node tail; | |
| 529 | + | |
| 530 | + /** | |
| 531 | + * The synchronization state. | |
| 532 | + */ | |
| 533 | + private volatile int state; | |
| 534 | + | |
| 535 | + /** | |
| 536 | + * Returns the current value of synchronization state. | |
| 537 | + * This operation has memory semantics of a <tt>volatile</tt> read. | |
| 538 | + * @return current state value | |
| 539 | + */ | |
| 540 | + protected final int getState() { | |
| 541 | + return state; | |
| 542 | + } | |
| 543 | + | |
| 544 | + /** | |
| 545 | + * Sets the value of synchronization state. | |
| 546 | + * This operation has memory semantics of a <tt>volatile</tt> write. | |
| 547 | + * @param newState the new state value | |
| 548 | + */ | |
| 549 | + protected final void setState(int newState) { | |
| 550 | + state = newState; | |
| 551 | + } | |
| 552 | + | |
| 553 | + /** | |
| 554 | + * Atomically sets synchronization state to the given updated | |
| 555 | + * value if the current state value equals the expected value. | |
| 556 | + * This operation has memory semantics of a <tt>volatile</tt> read | |
| 557 | + * and write. | |
| 558 | + * | |
| 559 | + * @param expect the expected value | |
| 560 | + * @param update the new value | |
| 561 | + * @return true if successful. False return indicates that the actual | |
| 562 | + * value was not equal to the expected value. | |
| 563 | + */ | |
| 564 | + protected final boolean compareAndSetState(int expect, int update) { | |
| 565 | + // See below for intrinsics setup to support this | |
| 566 | + return unsafe.compareAndSwapInt(this, stateOffset, expect, update); | |
| 567 | + } | |
| 568 | + | |
| 569 | + // Queuing utilities | |
| 570 | + | |
| 571 | + /** | |
| 572 | + * The number of nanoseconds for which it is faster to spin | |
| 573 | + * rather than to use timed park. A rough estimate suffices | |
| 574 | + * to improve responsiveness with very short timeouts. | |
| 575 | + */ | |
| 576 | + static final long spinForTimeoutThreshold = 1000L; | |
| 577 | + | |
| 578 | + /** | |
| 579 | + * Inserts node into queue, initializing if necessary. See picture above. | |
| 580 | + * @param node the node to insert | |
| 581 | + * @return node's predecessor | |
| 582 | + */ | |
| 583 | + private Node enq(final Node node) { | |
| 584 | + for (;;) { | |
| 585 | + Node t = tail; | |
| 586 | + if (t == null) { // Must initialize | |
| 587 | + if (compareAndSetHead(new Node())) | |
| 588 | + tail = head; | |
| 589 | + } else { | |
| 590 | + node.prev = t; | |
| 591 | + if (compareAndSetTail(t, node)) { | |
| 592 | + t.next = node; | |
| 593 | + return t; | |
| 594 | + } | |
| 595 | + } | |
| 596 | + } | |
| 597 | + } | |
| 598 | + | |
| 599 | + /** | |
| 600 | + * Creates and enqueues node for current thread and given mode. | |
| 601 | + * | |
| 602 | + * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared | |
| 603 | + * @return the new node | |
| 604 | + */ | |
| 605 | + private Node addWaiter(Node mode) { | |
| 606 | + Node node = new Node(Thread.currentThread(), mode); | |
| 607 | + // Try the fast path of enq; backup to full enq on failure | |
| 608 | + Node pred = tail; | |
| 609 | + if (pred != null) { | |
| 610 | + node.prev = pred; | |
| 611 | + if (compareAndSetTail(pred, node)) { | |
| 612 | + pred.next = node; | |
| 613 | + return node; | |
| 614 | + } | |
| 615 | + } | |
| 616 | + enq(node); | |
| 617 | + return node; | |
| 618 | + } | |
| 619 | + | |
| 620 | + /** | |
| 621 | + * Sets head of queue to be node, thus dequeuing. Called only by | |
| 622 | + * acquire methods. Also nulls out unused fields for sake of GC | |
| 623 | + * and to suppress unnecessary signals and traversals. | |
| 624 | + * | |
| 625 | + * @param node the node | |
| 626 | + */ | |
| 627 | + private void setHead(Node node) { | |
| 628 | + head = node; | |
| 629 | + node.thread = null; | |
| 630 | + node.prev = null; | |
| 631 | + } | |
| 632 | + | |
| 633 | + /** | |
| 634 | + * Wakes up node's successor, if one exists. | |
| 635 | + * | |
| 636 | + * @param node the node | |
| 637 | + */ | |
| 638 | + private void unparkSuccessor(Node node) { | |
| 639 | + /* | |
| 640 | + * If status is negative (i.e., possibly needing signal) try | |
| 641 | + * to clear in anticipation of signalling. It is OK if this | |
| 642 | + * fails or if status is changed by waiting thread. | |
| 643 | + */ | |
| 644 | + int ws = node.waitStatus; | |
| 645 | + if (ws < 0) | |
| 646 | + compareAndSetWaitStatus(node, ws, 0); | |
| 647 | + | |
| 648 | + /* | |
| 649 | + * Thread to unpark is held in successor, which is normally | |
| 650 | + * just the next node. But if cancelled or apparently null, | |
| 651 | + * traverse backwards from tail to find the actual | |
| 652 | + * non-cancelled successor. | |
| 653 | + */ | |
| 654 | + Node s = node.next; | |
| 655 | + if (s == null || s.waitStatus > 0) { | |
| 656 | + s = null; | |
| 657 | + for (Node t = tail; t != null && t != node; t = t.prev) | |
| 658 | + if (t.waitStatus <= 0) | |
| 659 | + s = t; | |
| 660 | + } | |
| 661 | + if (s != null) | |
| 662 | + LockSupport.unpark(s.thread); | |
| 663 | + } | |
| 664 | + | |
| 665 | + /** | |
| 666 | + * Release action for shared mode -- signal successor and ensure | |
| 667 | + * propagation. (Note: For exclusive mode, release just amounts | |
| 668 | + * to calling unparkSuccessor of head if it needs signal.) | |
| 669 | + */ | |
| 670 | + private void doReleaseShared() { | |
| 671 | + /* | |
| 672 | + * Ensure that a release propagates, even if there are other | |
| 673 | + * in-progress acquires/releases. This proceeds in the usual | |
| 674 | + * way of trying to unparkSuccessor of head if it needs | |
| 675 | + * signal. But if it does not, status is set to PROPAGATE to | |
| 676 | + * ensure that upon release, propagation continues. | |
| 677 | + * Additionally, we must loop in case a new node is added | |
| 678 | + * while we are doing this. Also, unlike other uses of | |
| 679 | + * unparkSuccessor, we need to know if CAS to reset status | |
| 680 | + * fails, if so rechecking. | |
| 681 | + */ | |
| 682 | + for (;;) { | |
| 683 | + Node h = head; | |
| 684 | + if (h != null && h != tail) { | |
| 685 | + int ws = h.waitStatus; | |
| 686 | + if (ws == Node.SIGNAL) { | |
| 687 | + if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) | |
| 688 | + continue; // loop to recheck cases | |
| 689 | + unparkSuccessor(h); | |
| 690 | + } | |
| 691 | + else if (ws == 0 && | |
| 692 | + !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) | |
| 693 | + continue; // loop on failed CAS | |
| 694 | + } | |
| 695 | + if (h == head) // loop if head changed | |
| 696 | + break; | |
| 697 | + } | |
| 698 | + } | |
| 699 | + | |
| 700 | + /** | |
| 701 | + * Sets head of queue, and checks if successor may be waiting | |
| 702 | + * in shared mode, if so propagating if either propagate > 0 or | |
| 703 | + * PROPAGATE status was set. | |
| 704 | + * | |
| 705 | + * @param node the node | |
| 706 | + * @param propagate the return value from a tryAcquireShared | |
| 707 | + */ | |
| 708 | + private void setHeadAndPropagate(Node node, int propagate) { | |
| 709 | + Node h = head; // Record old head for check below | |
| 710 | + setHead(node); | |
| 711 | + /* | |
| 712 | + * Try to signal next queued node if: | |
| 713 | + * Propagation was indicated by caller, | |
| 714 | + * or was recorded (as h.waitStatus) by a previous operation | |
| 715 | + * (note: this uses sign-check of waitStatus because | |
| 716 | + * PROPAGATE status may transition to SIGNAL.) | |
| 717 | + * and | |
| 718 | + * The next node is waiting in shared mode, | |
| 719 | + * or we don't know, because it appears null | |
| 720 | + * | |
| 721 | + * The conservatism in both of these checks may cause | |
| 722 | + * unnecessary wake-ups, but only when there are multiple | |
| 723 | + * racing acquires/releases, so most need signals now or soon | |
| 724 | + * anyway. | |
| 725 | + */ | |
| 726 | + if (propagate > 0 || h == null || h.waitStatus < 0) { | |
| 727 | + Node s = node.next; | |
| 728 | + if (s == null || s.isShared()) | |
| 729 | + doReleaseShared(); | |
| 730 | + } | |
| 731 | + } | |
| 732 | + | |
| 733 | + // Utilities for various versions of acquire | |
| 734 | + | |
| 735 | + /** | |
| 736 | + * Cancels an ongoing attempt to acquire. | |
| 737 | + * | |
| 738 | + * @param node the node | |
| 739 | + */ | |
| 740 | + private void cancelAcquire(Node node) { | |
| 741 | + // Ignore if node doesn't exist | |
| 742 | + if (node == null) | |
| 743 | + return; | |
| 744 | + | |
| 745 | + node.thread = null; | |
| 746 | + | |
| 747 | + // Skip cancelled predecessors | |
| 748 | + Node pred = node.prev; | |
| 749 | + while (pred.waitStatus > 0) | |
| 750 | + node.prev = pred = pred.prev; | |
| 751 | + | |
| 752 | + // predNext is the apparent node to unsplice. CASes below will | |
| 753 | + // fail if not, in which case, we lost race vs another cancel | |
| 754 | + // or signal, so no further action is necessary. | |
| 755 | + Node predNext = pred.next; | |
| 756 | + | |
| 757 | + // Can use unconditional write instead of CAS here. | |
| 758 | + // After this atomic step, other Nodes can skip past us. | |
| 759 | + // Before, we are free of interference from other threads. | |
| 760 | + node.waitStatus = Node.CANCELLED; | |
| 761 | + | |
| 762 | + // If we are the tail, remove ourselves. | |
| 763 | + if (node == tail && compareAndSetTail(node, pred)) { | |
| 764 | + compareAndSetNext(pred, predNext, null); | |
| 765 | + } else { | |
| 766 | + // If successor needs signal, try to set pred's next-link | |
| 767 | + // so it will get one. Otherwise wake it up to propagate. | |
| 768 | + int ws; | |
| 769 | + if (pred != head && | |
| 770 | + ((ws = pred.waitStatus) == Node.SIGNAL || | |
| 771 | + (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) && | |
| 772 | + pred.thread != null) { | |
| 773 | + Node next = node.next; | |
| 774 | + if (next != null && next.waitStatus <= 0) | |
| 775 | + compareAndSetNext(pred, predNext, next); | |
| 776 | + } else { | |
| 777 | + unparkSuccessor(node); | |
| 778 | + } | |
| 779 | + | |
| 780 | + node.next = node; // help GC | |
| 781 | + } | |
| 782 | + } | |
| 783 | + | |
| 784 | + /** | |
| 785 | + * Checks and updates status for a node that failed to acquire. | |
| 786 | + * Returns true if thread should block. This is the main signal | |
| 787 | + * control in all acquire loops. Requires that pred == node.prev | |
| 788 | + * | |
| 789 | + * @param pred node's predecessor holding status | |
| 790 | + * @param node the node | |
| 791 | + * @return {@code true} if thread should block | |
| 792 | + */ | |
| 793 | + private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) { | |
| 794 | + int ws = pred.waitStatus; | |
| 795 | + if (ws == Node.SIGNAL) | |
| 796 | + /* | |
| 797 | + * This node has already set status asking a release | |
| 798 | + * to signal it, so it can safely park. | |
| 799 | + */ | |
| 800 | + return true; | |
| 801 | + if (ws > 0) { | |
| 802 | + /* | |
| 803 | + * Predecessor was cancelled. Skip over predecessors and | |
| 804 | + * indicate retry. | |
| 805 | + */ | |
| 806 | + do { | |
| 807 | + node.prev = pred = pred.prev; | |
| 808 | + } while (pred.waitStatus > 0); | |
| 809 | + pred.next = node; | |
| 810 | + } else { | |
| 811 | + /* | |
| 812 | + * waitStatus must be 0 or PROPAGATE. Indicate that we | |
| 813 | + * need a signal, but don't park yet. Caller will need to | |
| 814 | + * retry to make sure it cannot acquire before parking. | |
| 815 | + */ | |
| 816 | + compareAndSetWaitStatus(pred, ws, Node.SIGNAL); | |
| 817 | + } | |
| 818 | + return false; | |
| 819 | + } | |
| 820 | + | |
| 821 | + /** | |
| 822 | + * Convenience method to interrupt current thread. | |
| 823 | + */ | |
| 824 | + private static void selfInterrupt() { | |
| 825 | + Thread.currentThread().interrupt(); | |
| 826 | + } | |
| 827 | + | |
| 828 | + /** | |
| 829 | + * Convenience method to park and then check if interrupted | |
| 830 | + * | |
| 831 | + * @return {@code true} if interrupted | |
| 832 | + */ | |
| 833 | + private final boolean parkAndCheckInterrupt() { | |
| 834 | + LockSupport.park(this); | |
| 835 | + return Thread.interrupted(); | |
| 836 | + } | |
| 837 | + | |
| 838 | + /* | |
| 839 | + * Various flavors of acquire, varying in exclusive/shared and | |
| 840 | + * control modes. Each is mostly the same, but annoyingly | |
| 841 | + * different. Only a little bit of factoring is possible due to | |
| 842 | + * interactions of exception mechanics (including ensuring that we | |
| 843 | + * cancel if tryAcquire throws exception) and other control, at | |
| 844 | + * least not without hurting performance too much. | |
| 845 | + */ | |
| 846 | + | |
| 847 | + /** | |
| 848 | + * Acquires in exclusive uninterruptible mode for thread already in | |
| 849 | + * queue. Used by condition wait methods as well as acquire. | |
| 850 | + * | |
| 851 | + * @param node the node | |
| 852 | + * @param arg the acquire argument | |
| 853 | + * @return {@code true} if interrupted while waiting | |
| 854 | + */ | |
| 855 | + final boolean acquireQueued(final Node node, int arg) { | |
| 856 | + boolean failed = true; | |
| 857 | + try { | |
| 858 | + boolean interrupted = false; | |
| 859 | + for (;;) { | |
| 860 | + final Node p = node.predecessor(); | |
| 861 | + if (p == head && tryAcquire(arg)) { | |
| 862 | + setHead(node); | |
| 863 | + p.next = null; // help GC | |
| 864 | + failed = false; | |
| 865 | + return interrupted; | |
| 866 | + } | |
| 867 | + if (shouldParkAfterFailedAcquire(p, node) && | |
| 868 | + parkAndCheckInterrupt()) | |
| 869 | + interrupted = true; | |
| 870 | + } | |
| 871 | + } finally { | |
| 872 | + if (failed) | |
| 873 | + cancelAcquire(node); | |
| 874 | + } | |
| 875 | + } | |
| 876 | + | |
| 877 | + /** | |
| 878 | + * Acquires in exclusive interruptible mode. | |
| 879 | + * @param arg the acquire argument | |
| 880 | + */ | |
| 881 | + private void doAcquireInterruptibly(int arg) | |
| 882 | + throws InterruptedException { | |
| 883 | + final Node node = addWaiter(Node.EXCLUSIVE); | |
| 884 | + boolean failed = true; | |
| 885 | + try { | |
| 886 | + for (;;) { | |
| 887 | + final Node p = node.predecessor(); | |
| 888 | + if (p == head && tryAcquire(arg)) { | |
| 889 | + setHead(node); | |
| 890 | + p.next = null; // help GC | |
| 891 | + failed = false; | |
| 892 | + return; | |
| 893 | + } | |
| 894 | + if (shouldParkAfterFailedAcquire(p, node) && | |
| 895 | + parkAndCheckInterrupt()) | |
| 896 | + throw new InterruptedException(); | |
| 897 | + } | |
| 898 | + } finally { | |
| 899 | + if (failed) | |
| 900 | + cancelAcquire(node); | |
| 901 | + } | |
| 902 | + } | |
| 903 | + | |
| 904 | + /** | |
| 905 | + * Acquires in exclusive timed mode. | |
| 906 | + * | |
| 907 | + * @param arg the acquire argument | |
| 908 | + * @param nanosTimeout max wait time | |
| 909 | + * @return {@code true} if acquired | |
| 910 | + */ | |
| 911 | + private boolean doAcquireNanos(int arg, long nanosTimeout) | |
| 912 | + throws InterruptedException { | |
| 913 | + long lastTime = System.nanoTime(); | |
| 914 | + final Node node = addWaiter(Node.EXCLUSIVE); | |
| 915 | + boolean failed = true; | |
| 916 | + try { | |
| 917 | + for (;;) { | |
| 918 | + final Node p = node.predecessor(); | |
| 919 | + if (p == head && tryAcquire(arg)) { | |
| 920 | + setHead(node); | |
| 921 | + p.next = null; // help GC | |
| 922 | + failed = false; | |
| 923 | + return true; | |
| 924 | + } | |
| 925 | + if (nanosTimeout <= 0) | |
| 926 | + return false; | |
| 927 | + if (shouldParkAfterFailedAcquire(p, node) && | |
| 928 | + nanosTimeout > spinForTimeoutThreshold) | |
| 929 | + LockSupport.parkNanos(this, nanosTimeout); | |
| 930 | + long now = System.nanoTime(); | |
| 931 | + nanosTimeout -= now - lastTime; | |
| 932 | + lastTime = now; | |
| 933 | + if (Thread.interrupted()) | |
| 934 | + throw new InterruptedException(); | |
| 935 | + } | |
| 936 | + } finally { | |
| 937 | + if (failed) | |
| 938 | + cancelAcquire(node); | |
| 939 | + } | |
| 940 | + } | |
| 941 | + | |
| 942 | + /** | |
| 943 | + * Acquires in shared uninterruptible mode. | |
| 944 | + * @param arg the acquire argument | |
| 945 | + */ | |
| 946 | + private void doAcquireShared(int arg) { | |
| 947 | + final Node node = addWaiter(Node.SHARED); | |
| 948 | + boolean failed = true; | |
| 949 | + try { | |
| 950 | + boolean interrupted = false; | |
| 951 | + for (;;) { | |
| 952 | + final Node p = node.predecessor(); | |
| 953 | + if (p == head) { | |
| 954 | + int r = tryAcquireShared(arg); | |
| 955 | + if (r >= 0) { | |
| 956 | + setHeadAndPropagate(node, r); | |
| 957 | + p.next = null; // help GC | |
| 958 | + if (interrupted) | |
| 959 | + selfInterrupt(); | |
| 960 | + failed = false; | |
| 961 | + return; | |
| 962 | + } | |
| 963 | + } | |
| 964 | + if (shouldParkAfterFailedAcquire(p, node) && | |
| 965 | + parkAndCheckInterrupt()) | |
| 966 | + interrupted = true; | |
| 967 | + } | |
| 968 | + } finally { | |
| 969 | + if (failed) | |
| 970 | + cancelAcquire(node); | |
| 971 | + } | |
| 972 | + } | |
| 973 | + | |
| 974 | + /** | |
| 975 | + * Acquires in shared interruptible mode. | |
| 976 | + * @param arg the acquire argument | |
| 977 | + */ | |
| 978 | + private void doAcquireSharedInterruptibly(int arg) | |
| 979 | + throws InterruptedException { | |
| 980 | + final Node node = addWaiter(Node.SHARED); | |
| 981 | + boolean failed = true; | |
| 982 | + try { | |
| 983 | + for (;;) { | |
| 984 | + final Node p = node.predecessor(); | |
| 985 | + if (p == head) { | |
| 986 | + int r = tryAcquireShared(arg); | |
| 987 | + if (r >= 0) { | |
| 988 | + setHeadAndPropagate(node, r); | |
| 989 | + p.next = null; // help GC | |
| 990 | + failed = false; | |
| 991 | + return; | |
| 992 | + } | |
| 993 | + } | |
| 994 | + if (shouldParkAfterFailedAcquire(p, node) && | |
| 995 | + parkAndCheckInterrupt()) | |
| 996 | + throw new InterruptedException(); | |
| 997 | + } | |
| 998 | + } finally { | |
| 999 | + if (failed) | |
| 1000 | + cancelAcquire(node); | |
| 1001 | + } | |
| 1002 | + } | |
| 1003 | + | |
| 1004 | + /** | |
| 1005 | + * Acquires in shared timed mode. | |
| 1006 | + * | |
| 1007 | + * @param arg the acquire argument | |
| 1008 | + * @param nanosTimeout max wait time | |
| 1009 | + * @return {@code true} if acquired | |
| 1010 | + */ | |
| 1011 | + private boolean doAcquireSharedNanos(int arg, long nanosTimeout) | |
| 1012 | + throws InterruptedException { | |
| 1013 | + | |
| 1014 | + long lastTime = System.nanoTime(); | |
| 1015 | + final Node node = addWaiter(Node.SHARED); | |
| 1016 | + boolean failed = true; | |
| 1017 | + try { | |
| 1018 | + for (;;) { | |
| 1019 | + final Node p = node.predecessor(); | |
| 1020 | + if (p == head) { | |
| 1021 | + int r = tryAcquireShared(arg); | |
| 1022 | + if (r >= 0) { | |
| 1023 | + setHeadAndPropagate(node, r); | |
| 1024 | + p.next = null; // help GC | |
| 1025 | + failed = false; | |
| 1026 | + return true; | |
| 1027 | + } | |
| 1028 | + } | |
| 1029 | + if (nanosTimeout <= 0) | |
| 1030 | + return false; | |
| 1031 | + if (shouldParkAfterFailedAcquire(p, node) && | |
| 1032 | + nanosTimeout > spinForTimeoutThreshold) | |
| 1033 | + LockSupport.parkNanos(this, nanosTimeout); | |
| 1034 | + long now = System.nanoTime(); | |
| 1035 | + nanosTimeout -= now - lastTime; | |
| 1036 | + lastTime = now; | |
| 1037 | + if (Thread.interrupted()) | |
| 1038 | + throw new InterruptedException(); | |
| 1039 | + } | |
| 1040 | + } finally { | |
| 1041 | + if (failed) | |
| 1042 | + cancelAcquire(node); | |
| 1043 | + } | |
| 1044 | + } | |
| 1045 | + | |
| 1046 | + // Main exported methods | |
| 1047 | + | |
| 1048 | + /** | |
| 1049 | + * Attempts to acquire in exclusive mode. This method should query | |
| 1050 | + * if the state of the object permits it to be acquired in the | |
| 1051 | + * exclusive mode, and if so to acquire it. | |
| 1052 | + * | |
| 1053 | + * <p>This method is always invoked by the thread performing | |
| 1054 | + * acquire. If this method reports failure, the acquire method | |
| 1055 | + * may queue the thread, if it is not already queued, until it is | |
| 1056 | + * signalled by a release from some other thread. This can be used | |
| 1057 | + * to implement method {@link Lock#tryLock()}. | |
| 1058 | + * | |
| 1059 | + * <p>The default | |
| 1060 | + * implementation throws {@link UnsupportedOperationException}. | |
| 1061 | + * | |
| 1062 | + * @param arg the acquire argument. This value is always the one | |
| 1063 | + * passed to an acquire method, or is the value saved on entry | |
| 1064 | + * to a condition wait. The value is otherwise uninterpreted | |
| 1065 | + * and can represent anything you like. | |
| 1066 | + * @return {@code true} if successful. Upon success, this object has | |
| 1067 | + * been acquired. | |
| 1068 | + * @throws IllegalMonitorStateException if acquiring would place this | |
| 1069 | + * synchronizer in an illegal state. This exception must be | |
| 1070 | + * thrown in a consistent fashion for synchronization to work | |
| 1071 | + * correctly. | |
| 1072 | + * @throws UnsupportedOperationException if exclusive mode is not supported | |
| 1073 | + */ | |
| 1074 | + protected boolean tryAcquire(int arg) { | |
| 1075 | + throw new UnsupportedOperationException(); | |
| 1076 | + } | |
| 1077 | + | |
| 1078 | + /** | |
| 1079 | + * Attempts to set the state to reflect a release in exclusive | |
| 1080 | + * mode. | |
| 1081 | + * | |
| 1082 | + * <p>This method is always invoked by the thread performing release. | |
| 1083 | + * | |
| 1084 | + * <p>The default implementation throws | |
| 1085 | + * {@link UnsupportedOperationException}. | |
| 1086 | + * | |
| 1087 | + * @param arg the release argument. This value is always the one | |
| 1088 | + * passed to a release method, or the current state value upon | |
| 1089 | + * entry to a condition wait. The value is otherwise | |
| 1090 | + * uninterpreted and can represent anything you like. | |
| 1091 | + * @return {@code true} if this object is now in a fully released | |
| 1092 | + * state, so that any waiting threads may attempt to acquire; | |
| 1093 | + * and {@code false} otherwise. | |
| 1094 | + * @throws IllegalMonitorStateException if releasing would place this | |
| 1095 | + * synchronizer in an illegal state. This exception must be | |
| 1096 | + * thrown in a consistent fashion for synchronization to work | |
| 1097 | + * correctly. | |
| 1098 | + * @throws UnsupportedOperationException if exclusive mode is not supported | |
| 1099 | + */ | |
| 1100 | + protected boolean tryRelease(int arg) { | |
| 1101 | + throw new UnsupportedOperationException(); | |
| 1102 | + } | |
| 1103 | + | |
| 1104 | + /** | |
| 1105 | + * Attempts to acquire in shared mode. This method should query if | |
| 1106 | + * the state of the object permits it to be acquired in the shared | |
| 1107 | + * mode, and if so to acquire it. | |
| 1108 | + * | |
| 1109 | + * <p>This method is always invoked by the thread performing | |
| 1110 | + * acquire. If this method reports failure, the acquire method | |
| 1111 | + * may queue the thread, if it is not already queued, until it is | |
| 1112 | + * signalled by a release from some other thread. | |
| 1113 | + * | |
| 1114 | + * <p>The default implementation throws {@link | |
| 1115 | + * UnsupportedOperationException}. | |
| 1116 | + * | |
| 1117 | + * @param arg the acquire argument. This value is always the one | |
| 1118 | + * passed to an acquire method, or is the value saved on entry | |
| 1119 | + * to a condition wait. The value is otherwise uninterpreted | |
| 1120 | + * and can represent anything you like. | |
| 1121 | + * @return a negative value on failure; zero if acquisition in shared | |
| 1122 | + * mode succeeded but no subsequent shared-mode acquire can | |
| 1123 | + * succeed; and a positive value if acquisition in shared | |
| 1124 | + * mode succeeded and subsequent shared-mode acquires might | |
| 1125 | + * also succeed, in which case a subsequent waiting thread | |
| 1126 | + * must check availability. (Support for three different | |
| 1127 | + * return values enables this method to be used in contexts | |
| 1128 | + * where acquires only sometimes act exclusively.) Upon | |
| 1129 | + * success, this object has been acquired. | |
| 1130 | + * @throws IllegalMonitorStateException if acquiring would place this | |
| 1131 | + * synchronizer in an illegal state. This exception must be | |
| 1132 | + * thrown in a consistent fashion for synchronization to work | |
| 1133 | + * correctly. | |
| 1134 | + * @throws UnsupportedOperationException if shared mode is not supported | |
| 1135 | + */ | |
| 1136 | + protected int tryAcquireShared(int arg) { | |
| 1137 | + throw new UnsupportedOperationException(); | |
| 1138 | + } | |
| 1139 | + | |
| 1140 | + /** | |
| 1141 | + * Attempts to set the state to reflect a release in shared mode. | |
| 1142 | + * | |
| 1143 | + * <p>This method is always invoked by the thread performing release. | |
| 1144 | + * | |
| 1145 | + * <p>The default implementation throws | |
| 1146 | + * {@link UnsupportedOperationException}. | |
| 1147 | + * | |
| 1148 | + * @param arg the release argument. This value is always the one | |
| 1149 | + * passed to a release method, or the current state value upon | |
| 1150 | + * entry to a condition wait. The value is otherwise | |
| 1151 | + * uninterpreted and can represent anything you like. | |
| 1152 | + * @return {@code true} if this release of shared mode may permit a | |
| 1153 | + * waiting acquire (shared or exclusive) to succeed; and | |
| 1154 | + * {@code false} otherwise | |
| 1155 | + * @throws IllegalMonitorStateException if releasing would place this | |
| 1156 | + * synchronizer in an illegal state. This exception must be | |
| 1157 | + * thrown in a consistent fashion for synchronization to work | |
| 1158 | + * correctly. | |
| 1159 | + * @throws UnsupportedOperationException if shared mode is not supported | |
| 1160 | + */ | |
| 1161 | + protected boolean tryReleaseShared(int arg) { | |
| 1162 | + throw new UnsupportedOperationException(); | |
| 1163 | + } | |
| 1164 | + | |
| 1165 | + /** | |
| 1166 | + * Returns {@code true} if synchronization is held exclusively with | |
| 1167 | + * respect to the current (calling) thread. This method is invoked | |
| 1168 | + * upon each call to a non-waiting {@link ConditionObject} method. | |
| 1169 | + * (Waiting methods instead invoke {@link #release}.) | |
| 1170 | + * | |
| 1171 | + * <p>The default implementation throws {@link | |
| 1172 | + * UnsupportedOperationException}. This method is invoked | |
| 1173 | + * internally only within {@link ConditionObject} methods, so need | |
| 1174 | + * not be defined if conditions are not used. | |
| 1175 | + * | |
| 1176 | + * @return {@code true} if synchronization is held exclusively; | |
| 1177 | + * {@code false} otherwise | |
| 1178 | + * @throws UnsupportedOperationException if conditions are not supported | |
| 1179 | + */ | |
| 1180 | + protected boolean isHeldExclusively() { | |
| 1181 | + throw new UnsupportedOperationException(); | |
| 1182 | + } | |
| 1183 | + | |
| 1184 | + /** | |
| 1185 | + * Acquires in exclusive mode, ignoring interrupts. Implemented | |
| 1186 | + * by invoking at least once {@link #tryAcquire}, | |
| 1187 | + * returning on success. Otherwise the thread is queued, possibly | |
| 1188 | + * repeatedly blocking and unblocking, invoking {@link | |
| 1189 | + * #tryAcquire} until success. This method can be used | |
| 1190 | + * to implement method {@link Lock#lock}. | |
| 1191 | + * | |
| 1192 | + * @param arg the acquire argument. This value is conveyed to | |
| 1193 | + * {@link #tryAcquire} but is otherwise uninterpreted and | |
| 1194 | + * can represent anything you like. | |
| 1195 | + */ | |
| 1196 | + public final void acquire(int arg) { | |
| 1197 | + if (!tryAcquire(arg) && | |
| 1198 | + acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) | |
| 1199 | + selfInterrupt(); | |
| 1200 | + } | |
| 1201 | + | |
| 1202 | + /** | |
| 1203 | + * Acquires in exclusive mode, aborting if interrupted. | |
| 1204 | + * Implemented by first checking interrupt status, then invoking | |
| 1205 | + * at least once {@link #tryAcquire}, returning on | |
| 1206 | + * success. Otherwise the thread is queued, possibly repeatedly | |
| 1207 | + * blocking and unblocking, invoking {@link #tryAcquire} | |
| 1208 | + * until success or the thread is interrupted. This method can be | |
| 1209 | + * used to implement method {@link Lock#lockInterruptibly}. | |
| 1210 | + * | |
| 1211 | + * @param arg the acquire argument. This value is conveyed to | |
| 1212 | + * {@link #tryAcquire} but is otherwise uninterpreted and | |
| 1213 | + * can represent anything you like. | |
| 1214 | + * @throws InterruptedException if the current thread is interrupted | |
| 1215 | + */ | |
| 1216 | + public final void acquireInterruptibly(int arg) | |
| 1217 | + throws InterruptedException { | |
| 1218 | + if (Thread.interrupted()) | |
| 1219 | + throw new InterruptedException(); | |
| 1220 | + if (!tryAcquire(arg)) | |
| 1221 | + doAcquireInterruptibly(arg); | |
| 1222 | + } | |
| 1223 | + | |
| 1224 | + /** | |
| 1225 | + * Attempts to acquire in exclusive mode, aborting if interrupted, | |
| 1226 | + * and failing if the given timeout elapses. Implemented by first | |
| 1227 | + * checking interrupt status, then invoking at least once {@link | |
| 1228 | + * #tryAcquire}, returning on success. Otherwise, the thread is | |
| 1229 | + * queued, possibly repeatedly blocking and unblocking, invoking | |
| 1230 | + * {@link #tryAcquire} until success or the thread is interrupted | |
| 1231 | + * or the timeout elapses. This method can be used to implement | |
| 1232 | + * method {@link Lock#tryLock(long, TimeUnit)}. | |
| 1233 | + * | |
| 1234 | + * @param arg the acquire argument. This value is conveyed to | |
| 1235 | + * {@link #tryAcquire} but is otherwise uninterpreted and | |
| 1236 | + * can represent anything you like. | |
| 1237 | + * @param nanosTimeout the maximum number of nanoseconds to wait | |
| 1238 | + * @return {@code true} if acquired; {@code false} if timed out | |
| 1239 | + * @throws InterruptedException if the current thread is interrupted | |
| 1240 | + */ | |
| 1241 | + public final boolean tryAcquireNanos(int arg, long nanosTimeout) | |
| 1242 | + throws InterruptedException { | |
| 1243 | + if (Thread.interrupted()) | |
| 1244 | + throw new InterruptedException(); | |
| 1245 | + return tryAcquire(arg) || | |
| 1246 | + doAcquireNanos(arg, nanosTimeout); | |
| 1247 | + } | |
| 1248 | + | |
| 1249 | + /** | |
| 1250 | + * Releases in exclusive mode. Implemented by unblocking one or | |
| 1251 | + * more threads if {@link #tryRelease} returns true. | |
| 1252 | + * This method can be used to implement method {@link Lock#unlock}. | |
| 1253 | + * | |
| 1254 | + * @param arg the release argument. This value is conveyed to | |
| 1255 | + * {@link #tryRelease} but is otherwise uninterpreted and | |
| 1256 | + * can represent anything you like. | |
| 1257 | + * @return the value returned from {@link #tryRelease} | |
| 1258 | + */ | |
| 1259 | + public final boolean release(int arg) { | |
| 1260 | + if (tryRelease(arg)) { | |
| 1261 | + Node h = head; | |
| 1262 | + if (h != null && h.waitStatus != 0) | |
| 1263 | + unparkSuccessor(h); | |
| 1264 | + return true; | |
| 1265 | + } | |
| 1266 | + return false; | |
| 1267 | + } | |
| 1268 | + | |
| 1269 | + /** | |
| 1270 | + * Acquires in shared mode, ignoring interrupts. Implemented by | |
| 1271 | + * first invoking at least once {@link #tryAcquireShared}, | |
| 1272 | + * returning on success. Otherwise the thread is queued, possibly | |
| 1273 | + * repeatedly blocking and unblocking, invoking {@link | |
| 1274 | + * #tryAcquireShared} until success. | |
| 1275 | + * | |
| 1276 | + * @param arg the acquire argument. This value is conveyed to | |
| 1277 | + * {@link #tryAcquireShared} but is otherwise uninterpreted | |
| 1278 | + * and can represent anything you like. | |
| 1279 | + */ | |
| 1280 | + public final void acquireShared(int arg) { | |
| 1281 | + if (tryAcquireShared(arg) < 0) | |
| 1282 | + doAcquireShared(arg); | |
| 1283 | + } | |
| 1284 | + | |
| 1285 | + /** | |
| 1286 | + * Acquires in shared mode, aborting if interrupted. Implemented | |
| 1287 | + * by first checking interrupt status, then invoking at least once | |
| 1288 | + * {@link #tryAcquireShared}, returning on success. Otherwise the | |
| 1289 | + * thread is queued, possibly repeatedly blocking and unblocking, | |
| 1290 | + * invoking {@link #tryAcquireShared} until success or the thread | |
| 1291 | + * is interrupted. | |
| 1292 | + * @param arg the acquire argument | |
| 1293 | + * This value is conveyed to {@link #tryAcquireShared} but is | |
| 1294 | + * otherwise uninterpreted and can represent anything | |
| 1295 | + * you like. | |
| 1296 | + * @throws InterruptedException if the current thread is interrupted | |
| 1297 | + */ | |
| 1298 | + public final void acquireSharedInterruptibly(int arg) | |
| 1299 | + throws InterruptedException { | |
| 1300 | + if (Thread.interrupted()) | |
| 1301 | + throw new InterruptedException(); | |
| 1302 | + if (tryAcquireShared(arg) < 0) | |
| 1303 | + doAcquireSharedInterruptibly(arg); | |
| 1304 | + } | |
| 1305 | + | |
| 1306 | + /** | |
| 1307 | + * Attempts to acquire in shared mode, aborting if interrupted, and | |
| 1308 | + * failing if the given timeout elapses. Implemented by first | |
| 1309 | + * checking interrupt status, then invoking at least once {@link | |
| 1310 | + * #tryAcquireShared}, returning on success. Otherwise, the | |
| 1311 | + * thread is queued, possibly repeatedly blocking and unblocking, | |
| 1312 | + * invoking {@link #tryAcquireShared} until success or the thread | |
| 1313 | + * is interrupted or the timeout elapses. | |
| 1314 | + * | |
| 1315 | + * @param arg the acquire argument. This value is conveyed to | |
| 1316 | + * {@link #tryAcquireShared} but is otherwise uninterpreted | |
| 1317 | + * and can represent anything you like. | |
| 1318 | + * @param nanosTimeout the maximum number of nanoseconds to wait | |
| 1319 | + * @return {@code true} if acquired; {@code false} if timed out | |
| 1320 | + * @throws InterruptedException if the current thread is interrupted | |
| 1321 | + */ | |
| 1322 | + public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout) | |
| 1323 | + throws InterruptedException { | |
| 1324 | + if (Thread.interrupted()) | |
| 1325 | + throw new InterruptedException(); | |
| 1326 | + return tryAcquireShared(arg) >= 0 || | |
| 1327 | + doAcquireSharedNanos(arg, nanosTimeout); | |
| 1328 | + } | |
| 1329 | + | |
| 1330 | + /** | |
| 1331 | + * Releases in shared mode. Implemented by unblocking one or more | |
| 1332 | + * threads if {@link #tryReleaseShared} returns true. | |
| 1333 | + * | |
| 1334 | + * @param arg the release argument. This value is conveyed to | |
| 1335 | + * {@link #tryReleaseShared} but is otherwise uninterpreted | |
| 1336 | + * and can represent anything you like. | |
| 1337 | + * @return the value returned from {@link #tryReleaseShared} | |
| 1338 | + */ | |
| 1339 | + public final boolean releaseShared(int arg) { | |
| 1340 | + if (tryReleaseShared(arg)) { | |
| 1341 | + doReleaseShared(); | |
| 1342 | + return true; | |
| 1343 | + } | |
| 1344 | + return false; | |
| 1345 | + } | |
| 1346 | + | |
| 1347 | + // Queue inspection methods | |
| 1348 | + | |
| 1349 | + /** | |
| 1350 | + * Queries whether any threads are waiting to acquire. Note that | |
| 1351 | + * because cancellations due to interrupts and timeouts may occur | |
| 1352 | + * at any time, a {@code true} return does not guarantee that any | |
| 1353 | + * other thread will ever acquire. | |
| 1354 | + * | |
| 1355 | + * <p>In this implementation, this operation returns in | |
| 1356 | + * constant time. | |
| 1357 | + * | |
| 1358 | + * @return {@code true} if there may be other threads waiting to acquire | |
| 1359 | + */ | |
| 1360 | + public final boolean hasQueuedThreads() { | |
| 1361 | + return head != tail; | |
| 1362 | + } | |
| 1363 | + | |
| 1364 | + /** | |
| 1365 | + * Queries whether any threads have ever contended to acquire this | |
| 1366 | + * synchronizer; that is if an acquire method has ever blocked. | |
| 1367 | + * | |
| 1368 | + * <p>In this implementation, this operation returns in | |
| 1369 | + * constant time. | |
| 1370 | + * | |
| 1371 | + * @return {@code true} if there has ever been contention | |
| 1372 | + */ | |
| 1373 | + public final boolean hasContended() { | |
| 1374 | + return head != null; | |
| 1375 | + } | |
| 1376 | + | |
| 1377 | + /** | |
| 1378 | + * Returns the first (longest-waiting) thread in the queue, or | |
| 1379 | + * {@code null} if no threads are currently queued. | |
| 1380 | + * | |
| 1381 | + * <p>In this implementation, this operation normally returns in | |
| 1382 | + * constant time, but may iterate upon contention if other threads are | |
| 1383 | + * concurrently modifying the queue. | |
| 1384 | + * | |
| 1385 | + * @return the first (longest-waiting) thread in the queue, or | |
| 1386 | + * {@code null} if no threads are currently queued | |
| 1387 | + */ | |
| 1388 | + public final Thread getFirstQueuedThread() { | |
| 1389 | + // handle only fast path, else relay | |
| 1390 | + return (head == tail) ? null : fullGetFirstQueuedThread(); | |
| 1391 | + } | |
| 1392 | + | |
| 1393 | + /** | |
| 1394 | + * Version of getFirstQueuedThread called when fastpath fails | |
| 1395 | + */ | |
| 1396 | + private Thread fullGetFirstQueuedThread() { | |
| 1397 | + /* | |
| 1398 | + * The first node is normally head.next. Try to get its | |
| 1399 | + * thread field, ensuring consistent reads: If thread | |
| 1400 | + * field is nulled out or s.prev is no longer head, then | |
| 1401 | + * some other thread(s) concurrently performed setHead in | |
| 1402 | + * between some of our reads. We try this twice before | |
| 1403 | + * resorting to traversal. | |
| 1404 | + */ | |
| 1405 | + Node h, s; | |
| 1406 | + Thread st; | |
| 1407 | + if (((h = head) != null && (s = h.next) != null && | |
| 1408 | + s.prev == head && (st = s.thread) != null) || | |
| 1409 | + ((h = head) != null && (s = h.next) != null && | |
| 1410 | + s.prev == head && (st = s.thread) != null)) | |
| 1411 | + return st; | |
| 1412 | + | |
| 1413 | + /* | |
| 1414 | + * Head's next field might not have been set yet, or may have | |
| 1415 | + * been unset after setHead. So we must check to see if tail | |
| 1416 | + * is actually first node. If not, we continue on, safely | |
| 1417 | + * traversing from tail back to head to find first, | |
| 1418 | + * guaranteeing termination. | |
| 1419 | + */ | |
| 1420 | + | |
| 1421 | + Node t = tail; | |
| 1422 | + Thread firstThread = null; | |
| 1423 | + while (t != null && t != head) { | |
| 1424 | + Thread tt = t.thread; | |
| 1425 | + if (tt != null) | |
| 1426 | + firstThread = tt; | |
| 1427 | + t = t.prev; | |
| 1428 | + } | |
| 1429 | + return firstThread; | |
| 1430 | + } | |
| 1431 | + | |
| 1432 | + /** | |
| 1433 | + * Returns true if the given thread is currently queued. | |
| 1434 | + * | |
| 1435 | + * <p>This implementation traverses the queue to determine | |
| 1436 | + * presence of the given thread. | |
| 1437 | + * | |
| 1438 | + * @param thread the thread | |
| 1439 | + * @return {@code true} if the given thread is on the queue | |
| 1440 | + * @throws NullPointerException if the thread is null | |
| 1441 | + */ | |
| 1442 | + public final boolean isQueued(Thread thread) { | |
| 1443 | + if (thread == null) | |
| 1444 | + throw new NullPointerException(); | |
| 1445 | + for (Node p = tail; p != null; p = p.prev) | |
| 1446 | + if (p.thread == thread) | |
| 1447 | + return true; | |
| 1448 | + return false; | |
| 1449 | + } | |
| 1450 | + | |
| 1451 | + /** | |
| 1452 | + * Returns {@code true} if the apparent first queued thread, if one | |
| 1453 | + * exists, is waiting in exclusive mode. If this method returns | |
| 1454 | + * {@code true}, and the current thread is attempting to acquire in | |
| 1455 | + * shared mode (that is, this method is invoked from {@link | |
| 1456 | + * #tryAcquireShared}) then it is guaranteed that the current thread | |
| 1457 | + * is not the first queued thread. Used only as a heuristic in | |
| 1458 | + * ReentrantReadWriteLock. | |
| 1459 | + */ | |
| 1460 | + final boolean apparentlyFirstQueuedIsExclusive() { | |
| 1461 | + Node h, s; | |
| 1462 | + return (h = head) != null && | |
| 1463 | + (s = h.next) != null && | |
| 1464 | + !s.isShared() && | |
| 1465 | + s.thread != null; | |
| 1466 | + } | |
| 1467 | + | |
| 1468 | + /** | |
| 1469 | + * Queries whether any threads have been waiting to acquire longer | |
| 1470 | + * than the current thread. | |
| 1471 | + * | |
| 1472 | + * <p>An invocation of this method is equivalent to (but may be | |
| 1473 | + * more efficient than): | |
| 1474 | + * <pre> {@code | |
| 1475 | + * getFirstQueuedThread() != Thread.currentThread() && | |
| 1476 | + * hasQueuedThreads()}</pre> | |
| 1477 | + * | |
| 1478 | + * <p>Note that because cancellations due to interrupts and | |
| 1479 | + * timeouts may occur at any time, a {@code true} return does not | |
| 1480 | + * guarantee that some other thread will acquire before the current | |
| 1481 | + * thread. Likewise, it is possible for another thread to win a | |
| 1482 | + * race to enqueue after this method has returned {@code false}, | |
| 1483 | + * due to the queue being empty. | |
| 1484 | + * | |
| 1485 | + * <p>This method is designed to be used by a fair synchronizer to | |
| 1486 | + * avoid <a href="AbstractQueuedSynchronizer#barging">barging</a>. | |
| 1487 | + * Such a synchronizer's {@link #tryAcquire} method should return | |
| 1488 | + * {@code false}, and its {@link #tryAcquireShared} method should | |
| 1489 | + * return a negative value, if this method returns {@code true} | |
| 1490 | + * (unless this is a reentrant acquire). For example, the {@code | |
| 1491 | + * tryAcquire} method for a fair, reentrant, exclusive mode | |
| 1492 | + * synchronizer might look like this: | |
| 1493 | + * | |
| 1494 | + * <pre> {@code | |
| 1495 | + * protected boolean tryAcquire(int arg) { | |
| 1496 | + * if (isHeldExclusively()) { | |
| 1497 | + * // A reentrant acquire; increment hold count | |
| 1498 | + * return true; | |
| 1499 | + * } else if (hasQueuedPredecessors()) { | |
| 1500 | + * return false; | |
| 1501 | + * } else { | |
| 1502 | + * // try to acquire normally | |
| 1503 | + * } | |
| 1504 | + * }}</pre> | |
| 1505 | + * | |
| 1506 | + * @return {@code true} if there is a queued thread preceding the | |
| 1507 | + * current thread, and {@code false} if the current thread | |
| 1508 | + * is at the head of the queue or the queue is empty | |
| 1509 | + * @since 1.7 | |
| 1510 | + */ | |
| 1511 | + public final boolean hasQueuedPredecessors() { | |
| 1512 | + // The correctness of this depends on head being initialized | |
| 1513 | + // before tail and on head.next being accurate if the current | |
| 1514 | + // thread is first in queue. | |
| 1515 | + Node t = tail; // Read fields in reverse initialization order | |
| 1516 | + Node h = head; | |
| 1517 | + Node s; | |
| 1518 | + return h != t && | |
| 1519 | + ((s = h.next) == null || s.thread != Thread.currentThread()); | |
| 1520 | + } | |
| 1521 | + | |
| 1522 | + | |
| 1523 | + // Instrumentation and monitoring methods | |
| 1524 | + | |
| 1525 | + /** | |
| 1526 | + * Returns an estimate of the number of threads waiting to | |
| 1527 | + * acquire. The value is only an estimate because the number of | |
| 1528 | + * threads may change dynamically while this method traverses | |
| 1529 | + * internal data structures. This method is designed for use in | |
| 1530 | + * monitoring system state, not for synchronization | |
| 1531 | + * control. | |
| 1532 | + * | |
| 1533 | + * @return the estimated number of threads waiting to acquire | |
| 1534 | + */ | |
| 1535 | + public final int getQueueLength() { | |
| 1536 | + int n = 0; | |
| 1537 | + for (Node p = tail; p != null; p = p.prev) { | |
| 1538 | + if (p.thread != null) | |
| 1539 | + ++n; | |
| 1540 | + } | |
| 1541 | + return n; | |
| 1542 | + } | |
| 1543 | + | |
| 1544 | + /** | |
| 1545 | + * Returns a collection containing threads that may be waiting to | |
| 1546 | + * acquire. Because the actual set of threads may change | |
| 1547 | + * dynamically while constructing this result, the returned | |
| 1548 | + * collection is only a best-effort estimate. The elements of the | |
| 1549 | + * returned collection are in no particular order. This method is | |
| 1550 | + * designed to facilitate construction of subclasses that provide | |
| 1551 | + * more extensive monitoring facilities. | |
| 1552 | + * | |
| 1553 | + * @return the collection of threads | |
| 1554 | + */ | |
| 1555 | + public final Collection<Thread> getQueuedThreads() { | |
| 1556 | + ArrayList<Thread> list = new ArrayList<Thread>(); | |
| 1557 | + for (Node p = tail; p != null; p = p.prev) { | |
| 1558 | + Thread t = p.thread; | |
| 1559 | + if (t != null) | |
| 1560 | + list.add(t); | |
| 1561 | + } | |
| 1562 | + return list; | |
| 1563 | + } | |
| 1564 | + | |
| 1565 | + /** | |
| 1566 | + * Returns a collection containing threads that may be waiting to | |
| 1567 | + * acquire in exclusive mode. This has the same properties | |
| 1568 | + * as {@link #getQueuedThreads} except that it only returns | |
| 1569 | + * those threads waiting due to an exclusive acquire. | |
| 1570 | + * | |
| 1571 | + * @return the collection of threads | |
| 1572 | + */ | |
| 1573 | + public final Collection<Thread> getExclusiveQueuedThreads() { | |
| 1574 | + ArrayList<Thread> list = new ArrayList<Thread>(); | |
| 1575 | + for (Node p = tail; p != null; p = p.prev) { | |
| 1576 | + if (!p.isShared()) { | |
| 1577 | + Thread t = p.thread; | |
| 1578 | + if (t != null) | |
| 1579 | + list.add(t); | |
| 1580 | + } | |
| 1581 | + } | |
| 1582 | + return list; | |
| 1583 | + } | |
| 1584 | + | |
| 1585 | + /** | |
| 1586 | + * Returns a collection containing threads that may be waiting to | |
| 1587 | + * acquire in shared mode. This has the same properties | |
| 1588 | + * as {@link #getQueuedThreads} except that it only returns | |
| 1589 | + * those threads waiting due to a shared acquire. | |
| 1590 | + * | |
| 1591 | + * @return the collection of threads | |
| 1592 | + */ | |
| 1593 | + public final Collection<Thread> getSharedQueuedThreads() { | |
| 1594 | + ArrayList<Thread> list = new ArrayList<Thread>(); | |
| 1595 | + for (Node p = tail; p != null; p = p.prev) { | |
| 1596 | + if (p.isShared()) { | |
| 1597 | + Thread t = p.thread; | |
| 1598 | + if (t != null) | |
| 1599 | + list.add(t); | |
| 1600 | + } | |
| 1601 | + } | |
| 1602 | + return list; | |
| 1603 | + } | |
| 1604 | + | |
| 1605 | + /** | |
| 1606 | + * Returns a string identifying this synchronizer, as well as its state. | |
| 1607 | + * The state, in brackets, includes the String {@code "State ="} | |
| 1608 | + * followed by the current value of {@link #getState}, and either | |
| 1609 | + * {@code "nonempty"} or {@code "empty"} depending on whether the | |
| 1610 | + * queue is empty. | |
| 1611 | + * | |
| 1612 | + * @return a string identifying this synchronizer, as well as its state | |
| 1613 | + */ | |
| 1614 | + public String toString() { | |
| 1615 | + int s = getState(); | |
| 1616 | + String q = hasQueuedThreads() ? "non" : ""; | |
| 1617 | + return super.toString() + | |
| 1618 | + "[State = " + s + ", " + q + "empty queue]"; | |
| 1619 | + } | |
| 1620 | + | |
| 1621 | + | |
| 1622 | + // Internal support methods for Conditions | |
| 1623 | + | |
| 1624 | + /** | |
| 1625 | + * Returns true if a node, always one that was initially placed on | |
| 1626 | + * a condition queue, is now waiting to reacquire on sync queue. | |
| 1627 | + * @param node the node | |
| 1628 | + * @return true if is reacquiring | |
| 1629 | + */ | |
| 1630 | + final boolean isOnSyncQueue(Node node) { | |
| 1631 | + if (node.waitStatus == Node.CONDITION || node.prev == null) | |
| 1632 | + return false; | |
| 1633 | + if (node.next != null) // If has successor, it must be on queue | |
| 1634 | + return true; | |
| 1635 | + /* | |
| 1636 | + * node.prev can be non-null, but not yet on queue because | |
| 1637 | + * the CAS to place it on queue can fail. So we have to | |
| 1638 | + * traverse from tail to make sure it actually made it. It | |
| 1639 | + * will always be near the tail in calls to this method, and | |
| 1640 | + * unless the CAS failed (which is unlikely), it will be | |
| 1641 | + * there, so we hardly ever traverse much. | |
| 1642 | + */ | |
| 1643 | + return findNodeFromTail(node); | |
| 1644 | + } | |
| 1645 | + | |
| 1646 | + /** | |
| 1647 | + * Returns true if node is on sync queue by searching backwards from tail. | |
| 1648 | + * Called only when needed by isOnSyncQueue. | |
| 1649 | + * @return true if present | |
| 1650 | + */ | |
| 1651 | + private boolean findNodeFromTail(Node node) { | |
| 1652 | + Node t = tail; | |
| 1653 | + for (;;) { | |
| 1654 | + if (t == node) | |
| 1655 | + return true; | |
| 1656 | + if (t == null) | |
| 1657 | + return false; | |
| 1658 | + t = t.prev; | |
| 1659 | + } | |
| 1660 | + } | |
| 1661 | + | |
| 1662 | + /** | |
| 1663 | + * Transfers a node from a condition queue onto sync queue. | |
| 1664 | + * Returns true if successful. | |
| 1665 | + * @param node the node | |
| 1666 | + * @return true if successfully transferred (else the node was | |
| 1667 | + * cancelled before signal). | |
| 1668 | + */ | |
| 1669 | + final boolean transferForSignal(Node node) { | |
| 1670 | + /* | |
| 1671 | + * If cannot change waitStatus, the node has been cancelled. | |
| 1672 | + */ | |
| 1673 | + if (!compareAndSetWaitStatus(node, Node.CONDITION, 0)) | |
| 1674 | + return false; | |
| 1675 | + | |
| 1676 | + /* | |
| 1677 | + * Splice onto queue and try to set waitStatus of predecessor to | |
| 1678 | + * indicate that thread is (probably) waiting. If cancelled or | |
| 1679 | + * attempt to set waitStatus fails, wake up to resync (in which | |
| 1680 | + * case the waitStatus can be transiently and harmlessly wrong). | |
| 1681 | + */ | |
| 1682 | + Node p = enq(node); | |
| 1683 | + int ws = p.waitStatus; | |
| 1684 | + if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL)) | |
| 1685 | + LockSupport.unpark(node.thread); | |
| 1686 | + return true; | |
| 1687 | + } | |
| 1688 | + | |
| 1689 | + /** | |
| 1690 | + * Transfers node, if necessary, to sync queue after a cancelled | |
| 1691 | + * wait. Returns true if thread was cancelled before being | |
| 1692 | + * signalled. | |
| 1693 | + * @param current the waiting thread | |
| 1694 | + * @param node its node | |
| 1695 | + * @return true if cancelled before the node was signalled | |
| 1696 | + */ | |
| 1697 | + final boolean transferAfterCancelledWait(Node node) { | |
| 1698 | + if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) { | |
| 1699 | + enq(node); | |
| 1700 | + return true; | |
| 1701 | + } | |
| 1702 | + /* | |
| 1703 | + * If we lost out to a signal(), then we can't proceed | |
| 1704 | + * until it finishes its enq(). Cancelling during an | |
| 1705 | + * incomplete transfer is both rare and transient, so just | |
| 1706 | + * spin. | |
| 1707 | + */ | |
| 1708 | + while (!isOnSyncQueue(node)) | |
| 1709 | + Thread.yield(); | |
| 1710 | + return false; | |
| 1711 | + } | |
| 1712 | + | |
| 1713 | + /** | |
| 1714 | + * Invokes release with current state value; returns saved state. | |
| 1715 | + * Cancels node and throws exception on failure. | |
| 1716 | + * @param node the condition node for this wait | |
| 1717 | + * @return previous sync state | |
| 1718 | + */ | |
| 1719 | + final int fullyRelease(Node node) { | |
| 1720 | + boolean failed = true; | |
| 1721 | + try { | |
| 1722 | + int savedState = getState(); | |
| 1723 | + if (release(savedState)) { | |
| 1724 | + failed = false; | |
| 1725 | + return savedState; | |
| 1726 | + } else { | |
| 1727 | + throw new IllegalMonitorStateException(); | |
| 1728 | + } | |
| 1729 | + } finally { | |
| 1730 | + if (failed) | |
| 1731 | + node.waitStatus = Node.CANCELLED; | |
| 1732 | + } | |
| 1733 | + } | |
| 1734 | + | |
| 1735 | + // Instrumentation methods for conditions | |
| 1736 | + | |
| 1737 | + /** | |
| 1738 | + * Queries whether the given ConditionObject | |
| 1739 | + * uses this synchronizer as its lock. | |
| 1740 | + * | |
| 1741 | + * @param condition the condition | |
| 1742 | + * @return <tt>true</tt> if owned | |
| 1743 | + * @throws NullPointerException if the condition is null | |
| 1744 | + */ | |
| 1745 | + public final boolean owns(ConditionObject condition) { | |
| 1746 | + if (condition == null) | |
| 1747 | + throw new NullPointerException(); | |
| 1748 | + return condition.isOwnedBy(this); | |
| 1749 | + } | |
| 1750 | + | |
| 1751 | + /** | |
| 1752 | + * Queries whether any threads are waiting on the given condition | |
| 1753 | + * associated with this synchronizer. Note that because timeouts | |
| 1754 | + * and interrupts may occur at any time, a <tt>true</tt> return | |
| 1755 | + * does not guarantee that a future <tt>signal</tt> will awaken | |
| 1756 | + * any threads. This method is designed primarily for use in | |
| 1757 | + * monitoring of the system state. | |
| 1758 | + * | |
| 1759 | + * @param condition the condition | |
| 1760 | + * @return <tt>true</tt> if there are any waiting threads | |
| 1761 | + * @throws IllegalMonitorStateException if exclusive synchronization | |
| 1762 | + * is not held | |
| 1763 | + * @throws IllegalArgumentException if the given condition is | |
| 1764 | + * not associated with this synchronizer | |
| 1765 | + * @throws NullPointerException if the condition is null | |
| 1766 | + */ | |
| 1767 | + public final boolean hasWaiters(ConditionObject condition) { | |
| 1768 | + if (!owns(condition)) | |
| 1769 | + throw new IllegalArgumentException("Not owner"); | |
| 1770 | + return condition.hasWaiters(); | |
| 1771 | + } | |
| 1772 | + | |
| 1773 | + /** | |
| 1774 | + * Returns an estimate of the number of threads waiting on the | |
| 1775 | + * given condition associated with this synchronizer. Note that | |
| 1776 | + * because timeouts and interrupts may occur at any time, the | |
| 1777 | + * estimate serves only as an upper bound on the actual number of | |
| 1778 | + * waiters. This method is designed for use in monitoring of the | |
| 1779 | + * system state, not for synchronization control. | |
| 1780 | + * | |
| 1781 | + * @param condition the condition | |
| 1782 | + * @return the estimated number of waiting threads | |
| 1783 | + * @throws IllegalMonitorStateException if exclusive synchronization | |
| 1784 | + * is not held | |
| 1785 | + * @throws IllegalArgumentException if the given condition is | |
| 1786 | + * not associated with this synchronizer | |
| 1787 | + * @throws NullPointerException if the condition is null | |
| 1788 | + */ | |
| 1789 | + public final int getWaitQueueLength(ConditionObject condition) { | |
| 1790 | + if (!owns(condition)) | |
| 1791 | + throw new IllegalArgumentException("Not owner"); | |
| 1792 | + return condition.getWaitQueueLength(); | |
| 1793 | + } | |
| 1794 | + | |
| 1795 | + /** | |
| 1796 | + * Returns a collection containing those threads that may be | |
| 1797 | + * waiting on the given condition associated with this | |
| 1798 | + * synchronizer. Because the actual set of threads may change | |
| 1799 | + * dynamically while constructing this result, the returned | |
| 1800 | + * collection is only a best-effort estimate. The elements of the | |
| 1801 | + * returned collection are in no particular order. | |
| 1802 | + * | |
| 1803 | + * @param condition the condition | |
| 1804 | + * @return the collection of threads | |
| 1805 | + * @throws IllegalMonitorStateException if exclusive synchronization | |
| 1806 | + * is not held | |
| 1807 | + * @throws IllegalArgumentException if the given condition is | |
| 1808 | + * not associated with this synchronizer | |
| 1809 | + * @throws NullPointerException if the condition is null | |
| 1810 | + */ | |
| 1811 | + public final Collection<Thread> getWaitingThreads(ConditionObject condition) { | |
| 1812 | + if (!owns(condition)) | |
| 1813 | + throw new IllegalArgumentException("Not owner"); | |
| 1814 | + return condition.getWaitingThreads(); | |
| 1815 | + } | |
| 1816 | + | |
| 1817 | + /** | |
| 1818 | + * Condition implementation for a {@link | |
| 1819 | + * AbstractQueuedSynchronizer} serving as the basis of a {@link | |
| 1820 | + * Lock} implementation. | |
| 1821 | + * | |
| 1822 | + * <p>Method documentation for this class describes mechanics, | |
| 1823 | + * not behavioral specifications from the point of view of Lock | |
| 1824 | + * and Condition users. Exported versions of this class will in | |
| 1825 | + * general need to be accompanied by documentation describing | |
| 1826 | + * condition semantics that rely on those of the associated | |
| 1827 | + * <tt>AbstractQueuedSynchronizer</tt>. | |
| 1828 | + * | |
| 1829 | + * <p>This class is Serializable, but all fields are transient, | |
| 1830 | + * so deserialized conditions have no waiters. | |
| 1831 | + */ | |
| 1832 | + public class ConditionObject implements Condition, java.io.Serializable { | |
| 1833 | + private static final long serialVersionUID = 1173984872572414699L; | |
| 1834 | + /** First node of condition queue. */ | |
| 1835 | + private transient Node firstWaiter; | |
| 1836 | + /** Last node of condition queue. */ | |
| 1837 | + private transient Node lastWaiter; | |
| 1838 | + | |
| 1839 | + /** | |
| 1840 | + * Creates a new <tt>ConditionObject</tt> instance. | |
| 1841 | + */ | |
| 1842 | + public ConditionObject() { } | |
| 1843 | + | |
| 1844 | + // Internal methods | |
| 1845 | + | |
| 1846 | + /** | |
| 1847 | + * Adds a new waiter to wait queue. | |
| 1848 | + * @return its new wait node | |
| 1849 | + */ | |
| 1850 | + private Node addConditionWaiter() { | |
| 1851 | + Node t = lastWaiter; | |
| 1852 | + // If lastWaiter is cancelled, clean out. | |
| 1853 | + if (t != null && t.waitStatus != Node.CONDITION) { | |
| 1854 | + unlinkCancelledWaiters(); | |
| 1855 | + t = lastWaiter; | |
| 1856 | + } | |
| 1857 | + Node node = new Node(Thread.currentThread(), Node.CONDITION); | |
| 1858 | + if (t == null) | |
| 1859 | + firstWaiter = node; | |
| 1860 | + else | |
| 1861 | + t.nextWaiter = node; | |
| 1862 | + lastWaiter = node; | |
| 1863 | + return node; | |
| 1864 | + } | |
| 1865 | + | |
| 1866 | + /** | |
| 1867 | + * Removes and transfers nodes until hit non-cancelled one or | |
| 1868 | + * null. Split out from signal in part to encourage compilers | |
| 1869 | + * to inline the case of no waiters. | |
| 1870 | + * @param first (non-null) the first node on condition queue | |
| 1871 | + */ | |
| 1872 | + private void doSignal(Node first) { | |
| 1873 | + do { | |
| 1874 | + if ( (firstWaiter = first.nextWaiter) == null) | |
| 1875 | + lastWaiter = null; | |
| 1876 | + first.nextWaiter = null; | |
| 1877 | + } while (!transferForSignal(first) && | |
| 1878 | + (first = firstWaiter) != null); | |
| 1879 | + } | |
| 1880 | + | |
| 1881 | + /** | |
| 1882 | + * Removes and transfers all nodes. | |
| 1883 | + * @param first (non-null) the first node on condition queue | |
| 1884 | + */ | |
| 1885 | + private void doSignalAll(Node first) { | |
| 1886 | + lastWaiter = firstWaiter = null; | |
| 1887 | + do { | |
| 1888 | + Node next = first.nextWaiter; | |
| 1889 | + first.nextWaiter = null; | |
| 1890 | + transferForSignal(first); | |
| 1891 | + first = next; | |
| 1892 | + } while (first != null); | |
| 1893 | + } | |
| 1894 | + | |
| 1895 | + /** | |
| 1896 | + * Unlinks cancelled waiter nodes from condition queue. | |
| 1897 | + * Called only while holding lock. This is called when | |
| 1898 | + * cancellation occurred during condition wait, and upon | |
| 1899 | + * insertion of a new waiter when lastWaiter is seen to have | |
| 1900 | + * been cancelled. This method is needed to avoid garbage | |
| 1901 | + * retention in the absence of signals. So even though it may | |
| 1902 | + * require a full traversal, it comes into play only when | |
| 1903 | + * timeouts or cancellations occur in the absence of | |
| 1904 | + * signals. It traverses all nodes rather than stopping at a | |
| 1905 | + * particular target to unlink all pointers to garbage nodes | |
| 1906 | + * without requiring many re-traversals during cancellation | |
| 1907 | + * storms. | |
| 1908 | + */ | |
| 1909 | + private void unlinkCancelledWaiters() { | |
| 1910 | + Node t = firstWaiter; | |
| 1911 | + Node trail = null; | |
| 1912 | + while (t != null) { | |
| 1913 | + Node next = t.nextWaiter; | |
| 1914 | + if (t.waitStatus != Node.CONDITION) { | |
| 1915 | + t.nextWaiter = null; | |
| 1916 | + if (trail == null) | |
| 1917 | + firstWaiter = next; | |
| 1918 | + else | |
| 1919 | + trail.nextWaiter = next; | |
| 1920 | + if (next == null) | |
| 1921 | + lastWaiter = trail; | |
| 1922 | + } | |
| 1923 | + else | |
| 1924 | + trail = t; | |
| 1925 | + t = next; | |
| 1926 | + } | |
| 1927 | + } | |
| 1928 | + | |
| 1929 | + // public methods | |
| 1930 | + | |
| 1931 | + /** | |
| 1932 | + * Moves the longest-waiting thread, if one exists, from the | |
| 1933 | + * wait queue for this condition to the wait queue for the | |
| 1934 | + * owning lock. | |
| 1935 | + * | |
| 1936 | + * @throws IllegalMonitorStateException if {@link #isHeldExclusively} | |
| 1937 | + * returns {@code false} | |
| 1938 | + */ | |
| 1939 | + public final void signal() { | |
| 1940 | + if (!isHeldExclusively()) | |
| 1941 | + throw new IllegalMonitorStateException(); | |
| 1942 | + Node first = firstWaiter; | |
| 1943 | + if (first != null) | |
| 1944 | + doSignal(first); | |
| 1945 | + } | |
| 1946 | + | |
| 1947 | + /** | |
| 1948 | + * Moves all threads from the wait queue for this condition to | |
| 1949 | + * the wait queue for the owning lock. | |
| 1950 | + * | |
| 1951 | + * @throws IllegalMonitorStateException if {@link #isHeldExclusively} | |
| 1952 | + * returns {@code false} | |
| 1953 | + */ | |
| 1954 | + public final void signalAll() { | |
| 1955 | + if (!isHeldExclusively()) | |
| 1956 | + throw new IllegalMonitorStateException(); | |
| 1957 | + Node first = firstWaiter; | |
| 1958 | + if (first != null) | |
| 1959 | + doSignalAll(first); | |
| 1960 | + } | |
| 1961 | + | |
| 1962 | + /** | |
| 1963 | + * Implements uninterruptible condition wait. | |
| 1964 | + * <ol> | |
| 1965 | + * <li> Save lock state returned by {@link #getState}. | |
| 1966 | + * <li> Invoke {@link #release} with | |
| 1967 | + * saved state as argument, throwing | |
| 1968 | + * IllegalMonitorStateException if it fails. | |
| 1969 | + * <li> Block until signalled. | |
| 1970 | + * <li> Reacquire by invoking specialized version of | |
| 1971 | + * {@link #acquire} with saved state as argument. | |
| 1972 | + * </ol> | |
| 1973 | + */ | |
| 1974 | + public final void awaitUninterruptibly() { | |
| 1975 | + Node node = addConditionWaiter(); | |
| 1976 | + int savedState = fullyRelease(node); | |
| 1977 | + boolean interrupted = false; | |
| 1978 | + while (!isOnSyncQueue(node)) { | |
| 1979 | + LockSupport.park(this); | |
| 1980 | + if (Thread.interrupted()) | |
| 1981 | + interrupted = true; | |
| 1982 | + } | |
| 1983 | + if (acquireQueued(node, savedState) || interrupted) | |
| 1984 | + selfInterrupt(); | |
| 1985 | + } | |
| 1986 | + | |
| 1987 | + /* | |
| 1988 | + * For interruptible waits, we need to track whether to throw | |
| 1989 | + * InterruptedException, if interrupted while blocked on | |
| 1990 | + * condition, versus reinterrupt current thread, if | |
| 1991 | + * interrupted while blocked waiting to re-acquire. | |
| 1992 | + */ | |
| 1993 | + | |
| 1994 | + /** Mode meaning to reinterrupt on exit from wait */ | |
| 1995 | + private static final int REINTERRUPT = 1; | |
| 1996 | + /** Mode meaning to throw InterruptedException on exit from wait */ | |
| 1997 | + private static final int THROW_IE = -1; | |
| 1998 | + | |
| 1999 | + /** | |
| 2000 | + * Checks for interrupt, returning THROW_IE if interrupted | |
| 2001 | + * before signalled, REINTERRUPT if after signalled, or | |
| 2002 | + * 0 if not interrupted. | |
| 2003 | + */ | |
| 2004 | + private int checkInterruptWhileWaiting(Node node) { | |
| 2005 | + return Thread.interrupted() ? | |
| 2006 | + (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) : | |
| 2007 | + 0; | |
| 2008 | + } | |
| 2009 | + | |
| 2010 | + /** | |
| 2011 | + * Throws InterruptedException, reinterrupts current thread, or | |
| 2012 | + * does nothing, depending on mode. | |
| 2013 | + */ | |
| 2014 | + private void reportInterruptAfterWait(int interruptMode) | |
| 2015 | + throws InterruptedException { | |
| 2016 | + if (interruptMode == THROW_IE) | |
| 2017 | + throw new InterruptedException(); | |
| 2018 | + else if (interruptMode == REINTERRUPT) | |
| 2019 | + selfInterrupt(); | |
| 2020 | + } | |
| 2021 | + | |
| 2022 | + /** | |
| 2023 | + * Implements interruptible condition wait. | |
| 2024 | + * <ol> | |
| 2025 | + * <li> If current thread is interrupted, throw InterruptedException. | |
| 2026 | + * <li> Save lock state returned by {@link #getState}. | |
| 2027 | + * <li> Invoke {@link #release} with | |
| 2028 | + * saved state as argument, throwing | |
| 2029 | + * IllegalMonitorStateException if it fails. | |
| 2030 | + * <li> Block until signalled or interrupted. | |
| 2031 | + * <li> Reacquire by invoking specialized version of | |
| 2032 | + * {@link #acquire} with saved state as argument. | |
| 2033 | + * <li> If interrupted while blocked in step 4, throw InterruptedException. | |
| 2034 | + * </ol> | |
| 2035 | + */ | |
| 2036 | + public final void await() throws InterruptedException { | |
| 2037 | + if (Thread.interrupted()) | |
| 2038 | + throw new InterruptedException(); | |
| 2039 | + Node node = addConditionWaiter(); | |
| 2040 | + int savedState = fullyRelease(node); | |
| 2041 | + int interruptMode = 0; | |
| 2042 | + while (!isOnSyncQueue(node)) { | |
| 2043 | + LockSupport.park(this); | |
| 2044 | + if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) | |
| 2045 | + break; | |
| 2046 | + } | |
| 2047 | + if (acquireQueued(node, savedState) && interruptMode != THROW_IE) | |
| 2048 | + interruptMode = REINTERRUPT; | |
| 2049 | + if (node.nextWaiter != null) // clean up if cancelled | |
| 2050 | + unlinkCancelledWaiters(); | |
| 2051 | + if (interruptMode != 0) | |
| 2052 | + reportInterruptAfterWait(interruptMode); | |
| 2053 | + } | |
| 2054 | + | |
| 2055 | + /** | |
| 2056 | + * Implements timed condition wait. | |
| 2057 | + * <ol> | |
| 2058 | + * <li> If current thread is interrupted, throw InterruptedException. | |
| 2059 | + * <li> Save lock state returned by {@link #getState}. | |
| 2060 | + * <li> Invoke {@link #release} with | |
| 2061 | + * saved state as argument, throwing | |
| 2062 | + * IllegalMonitorStateException if it fails. | |
| 2063 | + * <li> Block until signalled, interrupted, or timed out. | |
| 2064 | + * <li> Reacquire by invoking specialized version of | |
| 2065 | + * {@link #acquire} with saved state as argument. | |
| 2066 | + * <li> If interrupted while blocked in step 4, throw InterruptedException. | |
| 2067 | + * </ol> | |
| 2068 | + */ | |
| 2069 | + public final long awaitNanos(long nanosTimeout) | |
| 2070 | + throws InterruptedException { | |
| 2071 | + if (Thread.interrupted()) | |
| 2072 | + throw new InterruptedException(); | |
| 2073 | + Node node = addConditionWaiter(); | |
| 2074 | + int savedState = fullyRelease(node); | |
| 2075 | + long lastTime = System.nanoTime(); | |
| 2076 | + int interruptMode = 0; | |
| 2077 | + while (!isOnSyncQueue(node)) { | |
| 2078 | + if (nanosTimeout <= 0L) { | |
| 2079 | + transferAfterCancelledWait(node); | |
| 2080 | + break; | |
| 2081 | + } | |
| 2082 | + LockSupport.parkNanos(this, nanosTimeout); | |
| 2083 | + if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) | |
| 2084 | + break; | |
| 2085 | + | |
| 2086 | + long now = System.nanoTime(); | |
| 2087 | + nanosTimeout -= now - lastTime; | |
| 2088 | + lastTime = now; | |
| 2089 | + } | |
| 2090 | + if (acquireQueued(node, savedState) && interruptMode != THROW_IE) | |
| 2091 | + interruptMode = REINTERRUPT; | |
| 2092 | + if (node.nextWaiter != null) | |
| 2093 | + unlinkCancelledWaiters(); | |
| 2094 | + if (interruptMode != 0) | |
| 2095 | + reportInterruptAfterWait(interruptMode); | |
| 2096 | + return nanosTimeout - (System.nanoTime() - lastTime); | |
| 2097 | + } | |
| 2098 | + | |
| 2099 | + /** | |
| 2100 | + * Implements absolute timed condition wait. | |
| 2101 | + * <ol> | |
| 2102 | + * <li> If current thread is interrupted, throw InterruptedException. | |
| 2103 | + * <li> Save lock state returned by {@link #getState}. | |
| 2104 | + * <li> Invoke {@link #release} with | |
| 2105 | + * saved state as argument, throwing | |
| 2106 | + * IllegalMonitorStateException if it fails. | |
| 2107 | + * <li> Block until signalled, interrupted, or timed out. | |
| 2108 | + * <li> Reacquire by invoking specialized version of | |
| 2109 | + * {@link #acquire} with saved state as argument. | |
| 2110 | + * <li> If interrupted while blocked in step 4, throw InterruptedException. | |
| 2111 | + * <li> If timed out while blocked in step 4, return false, else true. | |
| 2112 | + * </ol> | |
| 2113 | + */ | |
| 2114 | + public final boolean awaitUntil(Date deadline) | |
| 2115 | + throws InterruptedException { | |
| 2116 | + if (deadline == null) | |
| 2117 | + throw new NullPointerException(); | |
| 2118 | + long abstime = deadline.getTime(); | |
| 2119 | + if (Thread.interrupted()) | |
| 2120 | + throw new InterruptedException(); | |
| 2121 | + Node node = addConditionWaiter(); | |
| 2122 | + int savedState = fullyRelease(node); | |
| 2123 | + boolean timedout = false; | |
| 2124 | + int interruptMode = 0; | |
| 2125 | + while (!isOnSyncQueue(node)) { | |
| 2126 | + if (System.currentTimeMillis() > abstime) { | |
| 2127 | + timedout = transferAfterCancelledWait(node); | |
| 2128 | + break; | |
| 2129 | + } | |
| 2130 | + LockSupport.parkUntil(this, abstime); | |
| 2131 | + if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) | |
| 2132 | + break; | |
| 2133 | + } | |
| 2134 | + if (acquireQueued(node, savedState) && interruptMode != THROW_IE) | |
| 2135 | + interruptMode = REINTERRUPT; | |
| 2136 | + if (node.nextWaiter != null) | |
| 2137 | + unlinkCancelledWaiters(); | |
| 2138 | + if (interruptMode != 0) | |
| 2139 | + reportInterruptAfterWait(interruptMode); | |
| 2140 | + return !timedout; | |
| 2141 | + } | |
| 2142 | + | |
| 2143 | + /** | |
| 2144 | + * Implements timed condition wait. | |
| 2145 | + * <ol> | |
| 2146 | + * <li> If current thread is interrupted, throw InterruptedException. | |
| 2147 | + * <li> Save lock state returned by {@link #getState}. | |
| 2148 | + * <li> Invoke {@link #release} with | |
| 2149 | + * saved state as argument, throwing | |
| 2150 | + * IllegalMonitorStateException if it fails. | |
| 2151 | + * <li> Block until signalled, interrupted, or timed out. | |
| 2152 | + * <li> Reacquire by invoking specialized version of | |
| 2153 | + * {@link #acquire} with saved state as argument. | |
| 2154 | + * <li> If interrupted while blocked in step 4, throw InterruptedException. | |
| 2155 | + * <li> If timed out while blocked in step 4, return false, else true. | |
| 2156 | + * </ol> | |
| 2157 | + */ | |
| 2158 | + public final boolean await(long time, TimeUnit unit) | |
| 2159 | + throws InterruptedException { | |
| 2160 | + if (unit == null) | |
| 2161 | + throw new NullPointerException(); | |
| 2162 | + long nanosTimeout = unit.toNanos(time); | |
| 2163 | + if (Thread.interrupted()) | |
| 2164 | + throw new InterruptedException(); | |
| 2165 | + Node node = addConditionWaiter(); | |
| 2166 | + int savedState = fullyRelease(node); | |
| 2167 | + long lastTime = System.nanoTime(); | |
| 2168 | + boolean timedout = false; | |
| 2169 | + int interruptMode = 0; | |
| 2170 | + while (!isOnSyncQueue(node)) { | |
| 2171 | + if (nanosTimeout <= 0L) { | |
| 2172 | + timedout = transferAfterCancelledWait(node); | |
| 2173 | + break; | |
| 2174 | + } | |
| 2175 | + if (nanosTimeout >= spinForTimeoutThreshold) | |
| 2176 | + LockSupport.parkNanos(this, nanosTimeout); | |
| 2177 | + if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) | |
| 2178 | + break; | |
| 2179 | + long now = System.nanoTime(); | |
| 2180 | + nanosTimeout -= now - lastTime; | |
| 2181 | + lastTime = now; | |
| 2182 | + } | |
| 2183 | + if (acquireQueued(node, savedState) && interruptMode != THROW_IE) | |
| 2184 | + interruptMode = REINTERRUPT; | |
| 2185 | + if (node.nextWaiter != null) | |
| 2186 | + unlinkCancelledWaiters(); | |
| 2187 | + if (interruptMode != 0) | |
| 2188 | + reportInterruptAfterWait(interruptMode); | |
| 2189 | + return !timedout; | |
| 2190 | + } | |
| 2191 | + | |
| 2192 | + // support for instrumentation | |
| 2193 | + | |
| 2194 | + /** | |
| 2195 | + * Returns true if this condition was created by the given | |
| 2196 | + * synchronization object. | |
| 2197 | + * | |
| 2198 | + * @return {@code true} if owned | |
| 2199 | + */ | |
| 2200 | + final boolean isOwnedBy(AbstractQueuedSynchronizer sync) { | |
| 2201 | + return sync == AbstractQueuedSynchronizer.this; | |
| 2202 | + } | |
| 2203 | + | |
| 2204 | + /** | |
| 2205 | + * Queries whether any threads are waiting on this condition. | |
| 2206 | + * Implements {@link AbstractQueuedSynchronizer#hasWaiters}. | |
| 2207 | + * | |
| 2208 | + * @return {@code true} if there are any waiting threads | |
| 2209 | + * @throws IllegalMonitorStateException if {@link #isHeldExclusively} | |
| 2210 | + * returns {@code false} | |
| 2211 | + */ | |
| 2212 | + protected final boolean hasWaiters() { | |
| 2213 | + if (!isHeldExclusively()) | |
| 2214 | + throw new IllegalMonitorStateException(); | |
| 2215 | + for (Node w = firstWaiter; w != null; w = w.nextWaiter) { | |
| 2216 | + if (w.waitStatus == Node.CONDITION) | |
| 2217 | + return true; | |
| 2218 | + } | |
| 2219 | + return false; | |
| 2220 | + } | |
| 2221 | + | |
| 2222 | + /** | |
| 2223 | + * Returns an estimate of the number of threads waiting on | |
| 2224 | + * this condition. | |
| 2225 | + * Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength}. | |
| 2226 | + * | |
| 2227 | + * @return the estimated number of waiting threads | |
| 2228 | + * @throws IllegalMonitorStateException if {@link #isHeldExclusively} | |
| 2229 | + * returns {@code false} | |
| 2230 | + */ | |
| 2231 | + protected final int getWaitQueueLength() { | |
| 2232 | + if (!isHeldExclusively()) | |
| 2233 | + throw new IllegalMonitorStateException(); | |
| 2234 | + int n = 0; | |
| 2235 | + for (Node w = firstWaiter; w != null; w = w.nextWaiter) { | |
| 2236 | + if (w.waitStatus == Node.CONDITION) | |
| 2237 | + ++n; | |
| 2238 | + } | |
| 2239 | + return n; | |
| 2240 | + } | |
| 2241 | + | |
| 2242 | + /** | |
| 2243 | + * Returns a collection containing those threads that may be | |
| 2244 | + * waiting on this Condition. | |
| 2245 | + * Implements {@link AbstractQueuedSynchronizer#getWaitingThreads}. | |
| 2246 | + * | |
| 2247 | + * @return the collection of threads | |
| 2248 | + * @throws IllegalMonitorStateException if {@link #isHeldExclusively} | |
| 2249 | + * returns {@code false} | |
| 2250 | + */ | |
| 2251 | + protected final Collection<Thread> getWaitingThreads() { | |
| 2252 | + if (!isHeldExclusively()) | |
| 2253 | + throw new IllegalMonitorStateException(); | |
| 2254 | + ArrayList<Thread> list = new ArrayList<Thread>(); | |
| 2255 | + for (Node w = firstWaiter; w != null; w = w.nextWaiter) { | |
| 2256 | + if (w.waitStatus == Node.CONDITION) { | |
| 2257 | + Thread t = w.thread; | |
| 2258 | + if (t != null) | |
| 2259 | + list.add(t); | |
| 2260 | + } | |
| 2261 | + } | |
| 2262 | + return list; | |
| 2263 | + } | |
| 2264 | + } | |
| 2265 | + | |
| 2266 | + /** | |
| 2267 | + * Setup to support compareAndSet. We need to natively implement | |
| 2268 | + * this here: For the sake of permitting future enhancements, we | |
| 2269 | + * cannot explicitly subclass AtomicInteger, which would be | |
| 2270 | + * efficient and useful otherwise. So, as the lesser of evils, we | |
| 2271 | + * natively implement using hotspot intrinsics API. And while we | |
| 2272 | + * are at it, we do the same for other CASable fields (which could | |
| 2273 | + * otherwise be done with atomic field updaters). | |
| 2274 | + */ | |
| 2275 | + private static final Unsafe unsafe = Unsafe.getUnsafe(); | |
| 2276 | + private static final long stateOffset; | |
| 2277 | + private static final long headOffset; | |
| 2278 | + private static final long tailOffset; | |
| 2279 | + private static final long waitStatusOffset; | |
| 2280 | + private static final long nextOffset; | |
| 2281 | + | |
| 2282 | + static { | |
| 2283 | + try { | |
| 2284 | + stateOffset = unsafe.objectFieldOffset | |
| 2285 | + (AbstractQueuedSynchronizer.class.getDeclaredField("state")); | |
| 2286 | + headOffset = unsafe.objectFieldOffset | |
| 2287 | + (AbstractQueuedSynchronizer.class.getDeclaredField("head")); | |
| 2288 | + tailOffset = unsafe.objectFieldOffset | |
| 2289 | + (AbstractQueuedSynchronizer.class.getDeclaredField("tail")); | |
| 2290 | + waitStatusOffset = unsafe.objectFieldOffset | |
| 2291 | + (Node.class.getDeclaredField("waitStatus")); | |
| 2292 | + nextOffset = unsafe.objectFieldOffset | |
| 2293 | + (Node.class.getDeclaredField("next")); | |
| 2294 | + | |
| 2295 | + } catch (Exception ex) { throw new Error(ex); } | |
| 2296 | + } | |
| 2297 | + | |
| 2298 | + /** | |
| 2299 | + * CAS head field. Used only by enq. | |
| 2300 | + */ | |
| 2301 | + private final boolean compareAndSetHead(Node update) { | |
| 2302 | + return unsafe.compareAndSwapObject(this, headOffset, null, update); | |
| 2303 | + } | |
| 2304 | + | |
| 2305 | + /** | |
| 2306 | + * CAS tail field. Used only by enq. | |
| 2307 | + */ | |
| 2308 | + private final boolean compareAndSetTail(Node expect, Node update) { | |
| 2309 | + return unsafe.compareAndSwapObject(this, tailOffset, expect, update); | |
| 2310 | + } | |
| 2311 | + | |
| 2312 | + /** | |
| 2313 | + * CAS waitStatus field of a node. | |
| 2314 | + */ | |
| 2315 | + private static final boolean compareAndSetWaitStatus(Node node, | |
| 2316 | + int expect, | |
| 2317 | + int update) { | |
| 2318 | + return unsafe.compareAndSwapInt(node, waitStatusOffset, | |
| 2319 | + expect, update); | |
| 2320 | + } | |
| 2321 | + | |
| 2322 | + /** | |
| 2323 | + * CAS next field of a node. | |
| 2324 | + */ | |
| 2325 | + private static final boolean compareAndSetNext(Node node, | |
| 2326 | + Node expect, | |
| 2327 | + Node update) { | |
| 2328 | + return unsafe.compareAndSwapObject(node, nextOffset, expect, update); | |
| 2329 | + } | |
| 2330 | +} | |
Binary file not shown.
| @@ -0,0 +1,488 @@ | ||
| 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 | +import java.util.concurrent.*; | |
| 38 | +import java.util.Date; | |
| 39 | + | |
| 40 | +/** | |
| 41 | + * {@code Condition} factors out the {@code Object} monitor | |
| 42 | + * methods ({@link Object#wait() wait}, {@link Object#notify notify} | |
| 43 | + * and {@link Object#notifyAll notifyAll}) into distinct objects to | |
| 44 | + * give the effect of having multiple wait-sets per object, by | |
| 45 | + * combining them with the use of arbitrary {@link Lock} implementations. | |
| 46 | + * Where a {@code Lock} replaces the use of {@code synchronized} methods | |
| 47 | + * and statements, a {@code Condition} replaces the use of the Object | |
| 48 | + * monitor methods. | |
| 49 | + * | |
| 50 | + * <p>Conditions (also known as <em>condition queues</em> or | |
| 51 | + * <em>condition variables</em>) provide a means for one thread to | |
| 52 | + * suspend execution (to "wait") until notified by another | |
| 53 | + * thread that some state condition may now be true. Because access | |
| 54 | + * to this shared state information occurs in different threads, it | |
| 55 | + * must be protected, so a lock of some form is associated with the | |
| 56 | + * condition. The key property that waiting for a condition provides | |
| 57 | + * is that it <em>atomically</em> releases the associated lock and | |
| 58 | + * suspends the current thread, just like {@code Object.wait}. | |
| 59 | + * | |
| 60 | + * <p>A {@code Condition} instance is intrinsically bound to a lock. | |
| 61 | + * To obtain a {@code Condition} instance for a particular {@link Lock} | |
| 62 | + * instance use its {@link Lock#newCondition newCondition()} method. | |
| 63 | + * | |
| 64 | + * <p>As an example, suppose we have a bounded buffer which supports | |
| 65 | + * {@code put} and {@code take} methods. If a | |
| 66 | + * {@code take} is attempted on an empty buffer, then the thread will block | |
| 67 | + * until an item becomes available; if a {@code put} is attempted on a | |
| 68 | + * full buffer, then the thread will block until a space becomes available. | |
| 69 | + * We would like to keep waiting {@code put} threads and {@code take} | |
| 70 | + * threads in separate wait-sets so that we can use the optimization of | |
| 71 | + * only notifying a single thread at a time when items or spaces become | |
| 72 | + * available in the buffer. This can be achieved using two | |
| 73 | + * {@link Condition} instances. | |
| 74 | + * <pre> | |
| 75 | + * class BoundedBuffer { | |
| 76 | + * <b>final Lock lock = new ReentrantLock();</b> | |
| 77 | + * final Condition notFull = <b>lock.newCondition(); </b> | |
| 78 | + * final Condition notEmpty = <b>lock.newCondition(); </b> | |
| 79 | + * | |
| 80 | + * final Object[] items = new Object[100]; | |
| 81 | + * int putptr, takeptr, count; | |
| 82 | + * | |
| 83 | + * public void put(Object x) throws InterruptedException { | |
| 84 | + * <b>lock.lock(); | |
| 85 | + * try {</b> | |
| 86 | + * while (count == items.length) | |
| 87 | + * <b>notFull.await();</b> | |
| 88 | + * items[putptr] = x; | |
| 89 | + * if (++putptr == items.length) putptr = 0; | |
| 90 | + * ++count; | |
| 91 | + * <b>notEmpty.signal();</b> | |
| 92 | + * <b>} finally { | |
| 93 | + * lock.unlock(); | |
| 94 | + * }</b> | |
| 95 | + * } | |
| 96 | + * | |
| 97 | + * public Object take() throws InterruptedException { | |
| 98 | + * <b>lock.lock(); | |
| 99 | + * try {</b> | |
| 100 | + * while (count == 0) | |
| 101 | + * <b>notEmpty.await();</b> | |
| 102 | + * Object x = items[takeptr]; | |
| 103 | + * if (++takeptr == items.length) takeptr = 0; | |
| 104 | + * --count; | |
| 105 | + * <b>notFull.signal();</b> | |
| 106 | + * return x; | |
| 107 | + * <b>} finally { | |
| 108 | + * lock.unlock(); | |
| 109 | + * }</b> | |
| 110 | + * } | |
| 111 | + * } | |
| 112 | + * </pre> | |
| 113 | + * | |
| 114 | + * (The {@link java.util.concurrent.ArrayBlockingQueue} class provides | |
| 115 | + * this functionality, so there is no reason to implement this | |
| 116 | + * sample usage class.) | |
| 117 | + * | |
| 118 | + * <p>A {@code Condition} implementation can provide behavior and semantics | |
| 119 | + * that is | |
| 120 | + * different from that of the {@code Object} monitor methods, such as | |
| 121 | + * guaranteed ordering for notifications, or not requiring a lock to be held | |
| 122 | + * when performing notifications. | |
| 123 | + * If an implementation provides such specialized semantics then the | |
| 124 | + * implementation must document those semantics. | |
| 125 | + * | |
| 126 | + * <p>Note that {@code Condition} instances are just normal objects and can | |
| 127 | + * themselves be used as the target in a {@code synchronized} statement, | |
| 128 | + * and can have their own monitor {@link Object#wait wait} and | |
| 129 | + * {@link Object#notify notification} methods invoked. | |
| 130 | + * Acquiring the monitor lock of a {@code Condition} instance, or using its | |
| 131 | + * monitor methods, has no specified relationship with acquiring the | |
| 132 | + * {@link Lock} associated with that {@code Condition} or the use of its | |
| 133 | + * {@linkplain #await waiting} and {@linkplain #signal signalling} methods. | |
| 134 | + * It is recommended that to avoid confusion you never use {@code Condition} | |
| 135 | + * instances in this way, except perhaps within their own implementation. | |
| 136 | + * | |
| 137 | + * <p>Except where noted, passing a {@code null} value for any parameter | |
| 138 | + * will result in a {@link NullPointerException} being thrown. | |
| 139 | + * | |
| 140 | + * <h3>Implementation Considerations</h3> | |
| 141 | + * | |
| 142 | + * <p>When waiting upon a {@code Condition}, a "<em>spurious | |
| 143 | + * wakeup</em>" is permitted to occur, in | |
| 144 | + * general, as a concession to the underlying platform semantics. | |
| 145 | + * This has little practical impact on most application programs as a | |
| 146 | + * {@code Condition} should always be waited upon in a loop, testing | |
| 147 | + * the state predicate that is being waited for. An implementation is | |
| 148 | + * free to remove the possibility of spurious wakeups but it is | |
| 149 | + * recommended that applications programmers always assume that they can | |
| 150 | + * occur and so always wait in a loop. | |
| 151 | + * | |
| 152 | + * <p>The three forms of condition waiting | |
| 153 | + * (interruptible, non-interruptible, and timed) may differ in their ease of | |
| 154 | + * implementation on some platforms and in their performance characteristics. | |
| 155 | + * In particular, it may be difficult to provide these features and maintain | |
| 156 | + * specific semantics such as ordering guarantees. | |
| 157 | + * Further, the ability to interrupt the actual suspension of the thread may | |
| 158 | + * not always be feasible to implement on all platforms. | |
| 159 | + * | |
| 160 | + * <p>Consequently, an implementation is not required to define exactly the | |
| 161 | + * same guarantees or semantics for all three forms of waiting, nor is it | |
| 162 | + * required to support interruption of the actual suspension of the thread. | |
| 163 | + * | |
| 164 | + * <p>An implementation is required to | |
| 165 | + * clearly document the semantics and guarantees provided by each of the | |
| 166 | + * waiting methods, and when an implementation does support interruption of | |
| 167 | + * thread suspension then it must obey the interruption semantics as defined | |
| 168 | + * in this interface. | |
| 169 | + * | |
| 170 | + * <p>As interruption generally implies cancellation, and checks for | |
| 171 | + * interruption are often infrequent, an implementation can favor responding | |
| 172 | + * to an interrupt over normal method return. This is true even if it can be | |
| 173 | + * shown that the interrupt occurred after another action that may have | |
| 174 | + * unblocked the thread. An implementation should document this behavior. | |
| 175 | + * | |
| 176 | + * @since 1.5 | |
| 177 | + * @author Doug Lea | |
| 178 | + */ | |
| 179 | +public interface Condition { | |
| 180 | + | |
| 181 | + /** | |
| 182 | + * Causes the current thread to wait until it is signalled or | |
| 183 | + * {@linkplain Thread#interrupt interrupted}. | |
| 184 | + * | |
| 185 | + * <p>The lock associated with this {@code Condition} is atomically | |
| 186 | + * released and the current thread becomes disabled for thread scheduling | |
| 187 | + * purposes and lies dormant until <em>one</em> of four things happens: | |
| 188 | + * <ul> | |
| 189 | + * <li>Some other thread invokes the {@link #signal} method for this | |
| 190 | + * {@code Condition} and the current thread happens to be chosen as the | |
| 191 | + * thread to be awakened; or | |
| 192 | + * <li>Some other thread invokes the {@link #signalAll} method for this | |
| 193 | + * {@code Condition}; or | |
| 194 | + * <li>Some other thread {@linkplain Thread#interrupt interrupts} the | |
| 195 | + * current thread, and interruption of thread suspension is supported; or | |
| 196 | + * <li>A "<em>spurious wakeup</em>" occurs. | |
| 197 | + * </ul> | |
| 198 | + * | |
| 199 | + * <p>In all cases, before this method can return the current thread must | |
| 200 | + * re-acquire the lock associated with this condition. When the | |
| 201 | + * thread returns it is <em>guaranteed</em> to hold this lock. | |
| 202 | + * | |
| 203 | + * <p>If the current thread: | |
| 204 | + * <ul> | |
| 205 | + * <li>has its interrupted status set on entry to this method; or | |
| 206 | + * <li>is {@linkplain Thread#interrupt interrupted} while waiting | |
| 207 | + * and interruption of thread suspension is supported, | |
| 208 | + * </ul> | |
| 209 | + * then {@link InterruptedException} is thrown and the current thread's | |
| 210 | + * interrupted status is cleared. It is not specified, in the first | |
| 211 | + * case, whether or not the test for interruption occurs before the lock | |
| 212 | + * is released. | |
| 213 | + * | |
| 214 | + * <p><b>Implementation Considerations</b> | |
| 215 | + * | |
| 216 | + * <p>The current thread is assumed to hold the lock associated with this | |
| 217 | + * {@code Condition} when this method is called. | |
| 218 | + * It is up to the implementation to determine if this is | |
| 219 | + * the case and if not, how to respond. Typically, an exception will be | |
| 220 | + * thrown (such as {@link IllegalMonitorStateException}) and the | |
| 221 | + * implementation must document that fact. | |
| 222 | + * | |
| 223 | + * <p>An implementation can favor responding to an interrupt over normal | |
| 224 | + * method return in response to a signal. In that case the implementation | |
| 225 | + * must ensure that the signal is redirected to another waiting thread, if | |
| 226 | + * there is one. | |
| 227 | + * | |
| 228 | + * @throws InterruptedException if the current thread is interrupted | |
| 229 | + * (and interruption of thread suspension is supported) | |
| 230 | + */ | |
| 231 | + void await() throws InterruptedException; | |
| 232 | + | |
| 233 | + /** | |
| 234 | + * Causes the current thread to wait until it is signalled. | |
| 235 | + * | |
| 236 | + * <p>The lock associated with this condition is atomically | |
| 237 | + * released and the current thread becomes disabled for thread scheduling | |
| 238 | + * purposes and lies dormant until <em>one</em> of three things happens: | |
| 239 | + * <ul> | |
| 240 | + * <li>Some other thread invokes the {@link #signal} method for this | |
| 241 | + * {@code Condition} and the current thread happens to be chosen as the | |
| 242 | + * thread to be awakened; or | |
| 243 | + * <li>Some other thread invokes the {@link #signalAll} method for this | |
| 244 | + * {@code Condition}; or | |
| 245 | + * <li>A "<em>spurious wakeup</em>" occurs. | |
| 246 | + * </ul> | |
| 247 | + * | |
| 248 | + * <p>In all cases, before this method can return the current thread must | |
| 249 | + * re-acquire the lock associated with this condition. When the | |
| 250 | + * thread returns it is <em>guaranteed</em> to hold this lock. | |
| 251 | + * | |
| 252 | + * <p>If the current thread's interrupted status is set when it enters | |
| 253 | + * this method, or it is {@linkplain Thread#interrupt interrupted} | |
| 254 | + * while waiting, it will continue to wait until signalled. When it finally | |
| 255 | + * returns from this method its interrupted status will still | |
| 256 | + * be set. | |
| 257 | + * | |
| 258 | + * <p><b>Implementation Considerations</b> | |
| 259 | + * | |
| 260 | + * <p>The current thread is assumed to hold the lock associated with this | |
| 261 | + * {@code Condition} when this method is called. | |
| 262 | + * It is up to the implementation to determine if this is | |
| 263 | + * the case and if not, how to respond. Typically, an exception will be | |
| 264 | + * thrown (such as {@link IllegalMonitorStateException}) and the | |
| 265 | + * implementation must document that fact. | |
| 266 | + */ | |
| 267 | + void awaitUninterruptibly(); | |
| 268 | + | |
| 269 | + /** | |
| 270 | + * Causes the current thread to wait until it is signalled or interrupted, | |
| 271 | + * or the specified waiting time elapses. | |
| 272 | + * | |
| 273 | + * <p>The lock associated with this condition is atomically | |
| 274 | + * released and the current thread becomes disabled for thread scheduling | |
| 275 | + * purposes and lies dormant until <em>one</em> of five things happens: | |
| 276 | + * <ul> | |
| 277 | + * <li>Some other thread invokes the {@link #signal} method for this | |
| 278 | + * {@code Condition} and the current thread happens to be chosen as the | |
| 279 | + * thread to be awakened; or | |
| 280 | + * <li>Some other thread invokes the {@link #signalAll} method for this | |
| 281 | + * {@code Condition}; or | |
| 282 | + * <li>Some other thread {@linkplain Thread#interrupt interrupts} the | |
| 283 | + * current thread, and interruption of thread suspension is supported; or | |
| 284 | + * <li>The specified waiting time elapses; or | |
| 285 | + * <li>A "<em>spurious wakeup</em>" occurs. | |
| 286 | + * </ul> | |
| 287 | + * | |
| 288 | + * <p>In all cases, before this method can return the current thread must | |
| 289 | + * re-acquire the lock associated with this condition. When the | |
| 290 | + * thread returns it is <em>guaranteed</em> to hold this lock. | |
| 291 | + * | |
| 292 | + * <p>If the current thread: | |
| 293 | + * <ul> | |
| 294 | + * <li>has its interrupted status set on entry to this method; or | |
| 295 | + * <li>is {@linkplain Thread#interrupt interrupted} while waiting | |
| 296 | + * and interruption of thread suspension is supported, | |
| 297 | + * </ul> | |
| 298 | + * then {@link InterruptedException} is thrown and the current thread's | |
| 299 | + * interrupted status is cleared. It is not specified, in the first | |
| 300 | + * case, whether or not the test for interruption occurs before the lock | |
| 301 | + * is released. | |
| 302 | + * | |
| 303 | + * <p>The method returns an estimate of the number of nanoseconds | |
| 304 | + * remaining to wait given the supplied {@code nanosTimeout} | |
| 305 | + * value upon return, or a value less than or equal to zero if it | |
| 306 | + * timed out. This value can be used to determine whether and how | |
| 307 | + * long to re-wait in cases where the wait returns but an awaited | |
| 308 | + * condition still does not hold. Typical uses of this method take | |
| 309 | + * the following form: | |
| 310 | + * | |
| 311 | + * <pre> {@code | |
| 312 | + * boolean aMethod(long timeout, TimeUnit unit) { | |
| 313 | + * long nanos = unit.toNanos(timeout); | |
| 314 | + * lock.lock(); | |
| 315 | + * try { | |
| 316 | + * while (!conditionBeingWaitedFor()) { | |
| 317 | + * if (nanos <= 0L) | |
| 318 | + * return false; | |
| 319 | + * nanos = theCondition.awaitNanos(nanos); | |
| 320 | + * } | |
| 321 | + * // ... | |
| 322 | + * } finally { | |
| 323 | + * lock.unlock(); | |
| 324 | + * } | |
| 325 | + * }}</pre> | |
| 326 | + * | |
| 327 | + * <p> Design note: This method requires a nanosecond argument so | |
| 328 | + * as to avoid truncation errors in reporting remaining times. | |
| 329 | + * Such precision loss would make it difficult for programmers to | |
| 330 | + * ensure that total waiting times are not systematically shorter | |
| 331 | + * than specified when re-waits occur. | |
| 332 | + * | |
| 333 | + * <p><b>Implementation Considerations</b> | |
| 334 | + * | |
| 335 | + * <p>The current thread is assumed to hold the lock associated with this | |
| 336 | + * {@code Condition} when this method is called. | |
| 337 | + * It is up to the implementation to determine if this is | |
| 338 | + * the case and if not, how to respond. Typically, an exception will be | |
| 339 | + * thrown (such as {@link IllegalMonitorStateException}) and the | |
| 340 | + * implementation must document that fact. | |
| 341 | + * | |
| 342 | + * <p>An implementation can favor responding to an interrupt over normal | |
| 343 | + * method return in response to a signal, or over indicating the elapse | |
| 344 | + * of the specified waiting time. In either case the implementation | |
| 345 | + * must ensure that the signal is redirected to another waiting thread, if | |
| 346 | + * there is one. | |
| 347 | + * | |
| 348 | + * @param nanosTimeout the maximum time to wait, in nanoseconds | |
| 349 | + * @return an estimate of the {@code nanosTimeout} value minus | |
| 350 | + * the time spent waiting upon return from this method. | |
| 351 | + * A positive value may be used as the argument to a | |
| 352 | + * subsequent call to this method to finish waiting out | |
| 353 | + * the desired time. A value less than or equal to zero | |
| 354 | + * indicates that no time remains. | |
| 355 | + * @throws InterruptedException if the current thread is interrupted | |
| 356 | + * (and interruption of thread suspension is supported) | |
| 357 | + */ | |
| 358 | + long awaitNanos(long nanosTimeout) throws InterruptedException; | |
| 359 | + | |
| 360 | + /** | |
| 361 | + * Causes the current thread to wait until it is signalled or interrupted, | |
| 362 | + * or the specified waiting time elapses. This method is behaviorally | |
| 363 | + * equivalent to:<br> | |
| 364 | + * <pre> | |
| 365 | + * awaitNanos(unit.toNanos(time)) > 0 | |
| 366 | + * </pre> | |
| 367 | + * @param time the maximum time to wait | |
| 368 | + * @param unit the time unit of the {@code time} argument | |
| 369 | + * @return {@code false} if the waiting time detectably elapsed | |
| 370 | + * before return from the method, else {@code true} | |
| 371 | + * @throws InterruptedException if the current thread is interrupted | |
| 372 | + * (and interruption of thread suspension is supported) | |
| 373 | + */ | |
| 374 | + boolean await(long time, TimeUnit unit) throws InterruptedException; | |
| 375 | + | |
| 376 | + /** | |
| 377 | + * Causes the current thread to wait until it is signalled or interrupted, | |
| 378 | + * or the specified deadline elapses. | |
| 379 | + * | |
| 380 | + * <p>The lock associated with this condition is atomically | |
| 381 | + * released and the current thread becomes disabled for thread scheduling | |
| 382 | + * purposes and lies dormant until <em>one</em> of five things happens: | |
| 383 | + * <ul> | |
| 384 | + * <li>Some other thread invokes the {@link #signal} method for this | |
| 385 | + * {@code Condition} and the current thread happens to be chosen as the | |
| 386 | + * thread to be awakened; or | |
| 387 | + * <li>Some other thread invokes the {@link #signalAll} method for this | |
| 388 | + * {@code Condition}; or | |
| 389 | + * <li>Some other thread {@linkplain Thread#interrupt interrupts} the | |
| 390 | + * current thread, and interruption of thread suspension is supported; or | |
| 391 | + * <li>The specified deadline elapses; or | |
| 392 | + * <li>A "<em>spurious wakeup</em>" occurs. | |
| 393 | + * </ul> | |
| 394 | + * | |
| 395 | + * <p>In all cases, before this method can return the current thread must | |
| 396 | + * re-acquire the lock associated with this condition. When the | |
| 397 | + * thread returns it is <em>guaranteed</em> to hold this lock. | |
| 398 | + * | |
| 399 | + * | |
| 400 | + * <p>If the current thread: | |
| 401 | + * <ul> | |
| 402 | + * <li>has its interrupted status set on entry to this method; or | |
| 403 | + * <li>is {@linkplain Thread#interrupt interrupted} while waiting | |
| 404 | + * and interruption of thread suspension is supported, | |
| 405 | + * </ul> | |
| 406 | + * then {@link InterruptedException} is thrown and the current thread's | |
| 407 | + * interrupted status is cleared. It is not specified, in the first | |
| 408 | + * case, whether or not the test for interruption occurs before the lock | |
| 409 | + * is released. | |
| 410 | + * | |
| 411 | + * | |
| 412 | + * <p>The return value indicates whether the deadline has elapsed, | |
| 413 | + * which can be used as follows: | |
| 414 | + * <pre> {@code | |
| 415 | + * boolean aMethod(Date deadline) { | |
| 416 | + * boolean stillWaiting = true; | |
| 417 | + * lock.lock(); | |
| 418 | + * try { | |
| 419 | + * while (!conditionBeingWaitedFor()) { | |
| 420 | + * if (!stillWaiting) | |
| 421 | + * return false; | |
| 422 | + * stillWaiting = theCondition.awaitUntil(deadline); | |
| 423 | + * } | |
| 424 | + * // ... | |
| 425 | + * } finally { | |
| 426 | + * lock.unlock(); | |
| 427 | + * } | |
| 428 | + * }}</pre> | |
| 429 | + * | |
| 430 | + * <p><b>Implementation Considerations</b> | |
| 431 | + * | |
| 432 | + * <p>The current thread is assumed to hold the lock associated with this | |
| 433 | + * {@code Condition} when this method is called. | |
| 434 | + * It is up to the implementation to determine if this is | |
| 435 | + * the case and if not, how to respond. Typically, an exception will be | |
| 436 | + * thrown (such as {@link IllegalMonitorStateException}) and the | |
| 437 | + * implementation must document that fact. | |
| 438 | + * | |
| 439 | + * <p>An implementation can favor responding to an interrupt over normal | |
| 440 | + * method return in response to a signal, or over indicating the passing | |
| 441 | + * of the specified deadline. In either case the implementation | |
| 442 | + * must ensure that the signal is redirected to another waiting thread, if | |
| 443 | + * there is one. | |
| 444 | + * | |
| 445 | + * @param deadline the absolute time to wait until | |
| 446 | + * @return {@code false} if the deadline has elapsed upon return, else | |
| 447 | + * {@code true} | |
| 448 | + * @throws InterruptedException if the current thread is interrupted | |
| 449 | + * (and interruption of thread suspension is supported) | |
| 450 | + */ | |
| 451 | + boolean awaitUntil(Date deadline) throws InterruptedException; | |
| 452 | + | |
| 453 | + /** | |
| 454 | + * Wakes up one waiting thread. | |
| 455 | + * | |
| 456 | + * <p>If any threads are waiting on this condition then one | |
| 457 | + * is selected for waking up. That thread must then re-acquire the | |
| 458 | + * lock before returning from {@code await}. | |
| 459 | + * | |
| 460 | + * <p><b>Implementation Considerations</b> | |
| 461 | + * | |
| 462 | + * <p>An implementation may (and typically does) require that the | |
| 463 | + * current thread hold the lock associated with this {@code | |
| 464 | + * Condition} when this method is called. Implementations must | |
| 465 | + * document this precondition and any actions taken if the lock is | |
| 466 | + * not held. Typically, an exception such as {@link | |
| 467 | + * IllegalMonitorStateException} will be thrown. | |
| 468 | + */ | |
| 469 | + void signal(); | |
| 470 | + | |
| 471 | + /** | |
| 472 | + * Wakes up all waiting threads. | |
| 473 | + * | |
| 474 | + * <p>If any threads are waiting on this condition then they are | |
| 475 | + * all woken up. Each thread must re-acquire the lock before it can | |
| 476 | + * return from {@code await}. | |
| 477 | + * | |
| 478 | + * <p><b>Implementation Considerations</b> | |
| 479 | + * | |
| 480 | + * <p>An implementation may (and typically does) require that the | |
| 481 | + * current thread hold the lock associated with this {@code | |
| 482 | + * Condition} when this method is called. Implementations must | |
| 483 | + * document this precondition and any actions taken if the lock is | |
| 484 | + * not held. Typically, an exception such as {@link | |
| 485 | + * IllegalMonitorStateException} will be thrown. | |
| 486 | + */ | |
| 487 | + void signalAll(); | |
| 488 | +} | |
Binary file not shown.
| @@ -0,0 +1,356 @@ | ||
| 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 | +import java.util.concurrent.TimeUnit; | |
| 38 | + | |
| 39 | +/** | |
| 40 | + * {@code Lock} implementations provide more extensive locking | |
| 41 | + * operations than can be obtained using {@code synchronized} methods | |
| 42 | + * and statements. They allow more flexible structuring, may have | |
| 43 | + * quite different properties, and may support multiple associated | |
| 44 | + * {@link Condition} objects. | |
| 45 | + * | |
| 46 | + * <p>A lock is a tool for controlling access to a shared resource by | |
| 47 | + * multiple threads. Commonly, a lock provides exclusive access to a | |
| 48 | + * shared resource: only one thread at a time can acquire the lock and | |
| 49 | + * all access to the shared resource requires that the lock be | |
| 50 | + * acquired first. However, some locks may allow concurrent access to | |
| 51 | + * a shared resource, such as the read lock of a {@link ReadWriteLock}. | |
| 52 | + * | |
| 53 | + * <p>The use of {@code synchronized} methods or statements provides | |
| 54 | + * access to the implicit monitor lock associated with every object, but | |
| 55 | + * forces all lock acquisition and release to occur in a block-structured way: | |
| 56 | + * when multiple locks are acquired they must be released in the opposite | |
| 57 | + * order, and all locks must be released in the same lexical scope in which | |
| 58 | + * they were acquired. | |
| 59 | + * | |
| 60 | + * <p>While the scoping mechanism for {@code synchronized} methods | |
| 61 | + * and statements makes it much easier to program with monitor locks, | |
| 62 | + * and helps avoid many common programming errors involving locks, | |
| 63 | + * there are occasions where you need to work with locks in a more | |
| 64 | + * flexible way. For example, some algorithms for traversing | |
| 65 | + * concurrently accessed data structures require the use of | |
| 66 | + * "hand-over-hand" or "chain locking": you | |
| 67 | + * acquire the lock of node A, then node B, then release A and acquire | |
| 68 | + * C, then release B and acquire D and so on. Implementations of the | |
| 69 | + * {@code Lock} interface enable the use of such techniques by | |
| 70 | + * allowing a lock to be acquired and released in different scopes, | |
| 71 | + * and allowing multiple locks to be acquired and released in any | |
| 72 | + * order. | |
| 73 | + * | |
| 74 | + * <p>With this increased flexibility comes additional | |
| 75 | + * responsibility. The absence of block-structured locking removes the | |
| 76 | + * automatic release of locks that occurs with {@code synchronized} | |
| 77 | + * methods and statements. In most cases, the following idiom | |
| 78 | + * should be used: | |
| 79 | + * | |
| 80 | + * <pre><tt> Lock l = ...; | |
| 81 | + * l.lock(); | |
| 82 | + * try { | |
| 83 | + * // access the resource protected by this lock | |
| 84 | + * } finally { | |
| 85 | + * l.unlock(); | |
| 86 | + * } | |
| 87 | + * </tt></pre> | |
| 88 | + * | |
| 89 | + * When locking and unlocking occur in different scopes, care must be | |
| 90 | + * taken to ensure that all code that is executed while the lock is | |
| 91 | + * held is protected by try-finally or try-catch to ensure that the | |
| 92 | + * lock is released when necessary. | |
| 93 | + * | |
| 94 | + * <p>{@code Lock} implementations provide additional functionality | |
| 95 | + * over the use of {@code synchronized} methods and statements by | |
| 96 | + * providing a non-blocking attempt to acquire a lock ({@link | |
| 97 | + * #tryLock()}), an attempt to acquire the lock that can be | |
| 98 | + * interrupted ({@link #lockInterruptibly}, and an attempt to acquire | |
| 99 | + * the lock that can timeout ({@link #tryLock(long, TimeUnit)}). | |
| 100 | + * | |
| 101 | + * <p>A {@code Lock} class can also provide behavior and semantics | |
| 102 | + * that is quite different from that of the implicit monitor lock, | |
| 103 | + * such as guaranteed ordering, non-reentrant usage, or deadlock | |
| 104 | + * detection. If an implementation provides such specialized semantics | |
| 105 | + * then the implementation must document those semantics. | |
| 106 | + * | |
| 107 | + * <p>Note that {@code Lock} instances are just normal objects and can | |
| 108 | + * themselves be used as the target in a {@code synchronized} statement. | |
| 109 | + * Acquiring the | |
| 110 | + * monitor lock of a {@code Lock} instance has no specified relationship | |
| 111 | + * with invoking any of the {@link #lock} methods of that instance. | |
| 112 | + * It is recommended that to avoid confusion you never use {@code Lock} | |
| 113 | + * instances in this way, except within their own implementation. | |
| 114 | + * | |
| 115 | + * <p>Except where noted, passing a {@code null} value for any | |
| 116 | + * parameter will result in a {@link NullPointerException} being | |
| 117 | + * thrown. | |
| 118 | + * | |
| 119 | + * <h3>Memory Synchronization</h3> | |
| 120 | + * | |
| 121 | + * <p>All {@code Lock} implementations <em>must</em> enforce the same | |
| 122 | + * memory synchronization semantics as provided by the built-in monitor | |
| 123 | + * lock, as described in section 17.4 of | |
| 124 | + * <cite>The Java™ Language Specification</cite>: | |
| 125 | + * <ul> | |
| 126 | + * <li>A successful {@code lock} operation has the same memory | |
| 127 | + * synchronization effects as a successful <em>Lock</em> action. | |
| 128 | + * <li>A successful {@code unlock} operation has the same | |
| 129 | + * memory synchronization effects as a successful <em>Unlock</em> action. | |
| 130 | + * </ul> | |
| 131 | + * | |
| 132 | + * Unsuccessful locking and unlocking operations, and reentrant | |
| 133 | + * locking/unlocking operations, do not require any memory | |
| 134 | + * synchronization effects. | |
| 135 | + * | |
| 136 | + * <h3>Implementation Considerations</h3> | |
| 137 | + * | |
| 138 | + * <p> The three forms of lock acquisition (interruptible, | |
| 139 | + * non-interruptible, and timed) may differ in their performance | |
| 140 | + * characteristics, ordering guarantees, or other implementation | |
| 141 | + * qualities. Further, the ability to interrupt the <em>ongoing</em> | |
| 142 | + * acquisition of a lock may not be available in a given {@code Lock} | |
| 143 | + * class. Consequently, an implementation is not required to define | |
| 144 | + * exactly the same guarantees or semantics for all three forms of | |
| 145 | + * lock acquisition, nor is it required to support interruption of an | |
| 146 | + * ongoing lock acquisition. An implementation is required to clearly | |
| 147 | + * document the semantics and guarantees provided by each of the | |
| 148 | + * locking methods. It must also obey the interruption semantics as | |
| 149 | + * defined in this interface, to the extent that interruption of lock | |
| 150 | + * acquisition is supported: which is either totally, or only on | |
| 151 | + * method entry. | |
| 152 | + * | |
| 153 | + * <p>As interruption generally implies cancellation, and checks for | |
| 154 | + * interruption are often infrequent, an implementation can favor responding | |
| 155 | + * to an interrupt over normal method return. This is true even if it can be | |
| 156 | + * shown that the interrupt occurred after another action may have unblocked | |
| 157 | + * the thread. An implementation should document this behavior. | |
| 158 | + * | |
| 159 | + * @see ReentrantLock | |
| 160 | + * @see Condition | |
| 161 | + * @see ReadWriteLock | |
| 162 | + * | |
| 163 | + * @since 1.5 | |
| 164 | + * @author Doug Lea | |
| 165 | + */ | |
| 166 | +public interface Lock { | |
| 167 | + | |
| 168 | + /** | |
| 169 | + * Acquires the lock. | |
| 170 | + * | |
| 171 | + * <p>If the lock is not available then the current thread becomes | |
| 172 | + * disabled for thread scheduling purposes and lies dormant until the | |
| 173 | + * lock has been acquired. | |
| 174 | + * | |
| 175 | + * <p><b>Implementation Considerations</b> | |
| 176 | + * | |
| 177 | + * <p>A {@code Lock} implementation may be able to detect erroneous use | |
| 178 | + * of the lock, such as an invocation that would cause deadlock, and | |
| 179 | + * may throw an (unchecked) exception in such circumstances. The | |
| 180 | + * circumstances and the exception type must be documented by that | |
| 181 | + * {@code Lock} implementation. | |
| 182 | + */ | |
| 183 | + void lock(); | |
| 184 | + | |
| 185 | + /** | |
| 186 | + * Acquires the lock unless the current thread is | |
| 187 | + * {@linkplain Thread#interrupt interrupted}. | |
| 188 | + * | |
| 189 | + * <p>Acquires the lock if it is available and returns immediately. | |
| 190 | + * | |
| 191 | + * <p>If the lock is not available then the current thread becomes | |
| 192 | + * disabled for thread scheduling purposes and lies dormant until | |
| 193 | + * one of two things happens: | |
| 194 | + * | |
| 195 | + * <ul> | |
| 196 | + * <li>The lock is acquired by the current thread; or | |
| 197 | + * <li>Some other thread {@linkplain Thread#interrupt interrupts} the | |
| 198 | + * current thread, and interruption of lock acquisition is supported. | |
| 199 | + * </ul> | |
| 200 | + * | |
| 201 | + * <p>If the current thread: | |
| 202 | + * <ul> | |
| 203 | + * <li>has its interrupted status set on entry to this method; or | |
| 204 | + * <li>is {@linkplain Thread#interrupt interrupted} while acquiring the | |
| 205 | + * lock, and interruption of lock acquisition is supported, | |
| 206 | + * </ul> | |
| 207 | + * then {@link InterruptedException} is thrown and the current thread's | |
| 208 | + * interrupted status is cleared. | |
| 209 | + * | |
| 210 | + * <p><b>Implementation Considerations</b> | |
| 211 | + * | |
| 212 | + * <p>The ability to interrupt a lock acquisition in some | |
| 213 | + * implementations may not be possible, and if possible may be an | |
| 214 | + * expensive operation. The programmer should be aware that this | |
| 215 | + * may be the case. An implementation should document when this is | |
| 216 | + * the case. | |
| 217 | + * | |
| 218 | + * <p>An implementation can favor responding to an interrupt over | |
| 219 | + * normal method return. | |
| 220 | + * | |
| 221 | + * <p>A {@code Lock} implementation may be able to detect | |
| 222 | + * erroneous use of the lock, such as an invocation that would | |
| 223 | + * cause deadlock, and may throw an (unchecked) exception in such | |
| 224 | + * circumstances. The circumstances and the exception type must | |
| 225 | + * be documented by that {@code Lock} implementation. | |
| 226 | + * | |
| 227 | + * @throws InterruptedException if the current thread is | |
| 228 | + * interrupted while acquiring the lock (and interruption | |
| 229 | + * of lock acquisition is supported). | |
| 230 | + */ | |
| 231 | + void lockInterruptibly() throws InterruptedException; | |
| 232 | + | |
| 233 | + /** | |
| 234 | + * Acquires the lock only if it is free at the time of invocation. | |
| 235 | + * | |
| 236 | + * <p>Acquires the lock if it is available and returns immediately | |
| 237 | + * with the value {@code true}. | |
| 238 | + * If the lock is not available then this method will return | |
| 239 | + * immediately with the value {@code false}. | |
| 240 | + * | |
| 241 | + * <p>A typical usage idiom for this method would be: | |
| 242 | + * <pre> | |
| 243 | + * Lock lock = ...; | |
| 244 | + * if (lock.tryLock()) { | |
| 245 | + * try { | |
| 246 | + * // manipulate protected state | |
| 247 | + * } finally { | |
| 248 | + * lock.unlock(); | |
| 249 | + * } | |
| 250 | + * } else { | |
| 251 | + * // perform alternative actions | |
| 252 | + * } | |
| 253 | + * </pre> | |
| 254 | + * This usage ensures that the lock is unlocked if it was acquired, and | |
| 255 | + * doesn't try to unlock if the lock was not acquired. | |
| 256 | + * | |
| 257 | + * @return {@code true} if the lock was acquired and | |
| 258 | + * {@code false} otherwise | |
| 259 | + */ | |
| 260 | + boolean tryLock(); | |
| 261 | + | |
| 262 | + /** | |
| 263 | + * Acquires the lock if it is free within the given waiting time and the | |
| 264 | + * current thread has not been {@linkplain Thread#interrupt interrupted}. | |
| 265 | + * | |
| 266 | + * <p>If the lock is available this method returns immediately | |
| 267 | + * with the value {@code true}. | |
| 268 | + * If the lock is not available then | |
| 269 | + * the current thread becomes disabled for thread scheduling | |
| 270 | + * purposes and lies dormant until one of three things happens: | |
| 271 | + * <ul> | |
| 272 | + * <li>The lock is acquired by the current thread; or | |
| 273 | + * <li>Some other thread {@linkplain Thread#interrupt interrupts} the | |
| 274 | + * current thread, and interruption of lock acquisition is supported; or | |
| 275 | + * <li>The specified waiting time elapses | |
| 276 | + * </ul> | |
| 277 | + * | |
| 278 | + * <p>If the lock is acquired then the value {@code true} is returned. | |
| 279 | + * | |
| 280 | + * <p>If the current thread: | |
| 281 | + * <ul> | |
| 282 | + * <li>has its interrupted status set on entry to this method; or | |
| 283 | + * <li>is {@linkplain Thread#interrupt interrupted} while acquiring | |
| 284 | + * the lock, and interruption of lock acquisition is supported, | |
| 285 | + * </ul> | |
| 286 | + * then {@link InterruptedException} is thrown and the current thread's | |
| 287 | + * interrupted status is cleared. | |
| 288 | + * | |
| 289 | + * <p>If the specified waiting time elapses then the value {@code false} | |
| 290 | + * is returned. | |
| 291 | + * If the time is | |
| 292 | + * less than or equal to zero, the method will not wait at all. | |
| 293 | + * | |
| 294 | + * <p><b>Implementation Considerations</b> | |
| 295 | + * | |
| 296 | + * <p>The ability to interrupt a lock acquisition in some implementations | |
| 297 | + * may not be possible, and if possible may | |
| 298 | + * be an expensive operation. | |
| 299 | + * The programmer should be aware that this may be the case. An | |
| 300 | + * implementation should document when this is the case. | |
| 301 | + * | |
| 302 | + * <p>An implementation can favor responding to an interrupt over normal | |
| 303 | + * method return, or reporting a timeout. | |
| 304 | + * | |
| 305 | + * <p>A {@code Lock} implementation may be able to detect | |
| 306 | + * erroneous use of the lock, such as an invocation that would cause | |
| 307 | + * deadlock, and may throw an (unchecked) exception in such circumstances. | |
| 308 | + * The circumstances and the exception type must be documented by that | |
| 309 | + * {@code Lock} implementation. | |
| 310 | + * | |
| 311 | + * @param time the maximum time to wait for the lock | |
| 312 | + * @param unit the time unit of the {@code time} argument | |
| 313 | + * @return {@code true} if the lock was acquired and {@code false} | |
| 314 | + * if the waiting time elapsed before the lock was acquired | |
| 315 | + * | |
| 316 | + * @throws InterruptedException if the current thread is interrupted | |
| 317 | + * while acquiring the lock (and interruption of lock | |
| 318 | + * acquisition is supported) | |
| 319 | + */ | |
| 320 | + boolean tryLock(long time, TimeUnit unit) throws InterruptedException; | |
| 321 | + | |
| 322 | + /** | |
| 323 | + * Releases the lock. | |
| 324 | + * | |
| 325 | + * <p><b>Implementation Considerations</b> | |
| 326 | + * | |
| 327 | + * <p>A {@code Lock} implementation will usually impose | |
| 328 | + * restrictions on which thread can release a lock (typically only the | |
| 329 | + * holder of the lock can release it) and may throw | |
| 330 | + * an (unchecked) exception if the restriction is violated. | |
| 331 | + * Any restrictions and the exception | |
| 332 | + * type must be documented by that {@code Lock} implementation. | |
| 333 | + */ | |
| 334 | + void unlock(); | |
| 335 | + | |
| 336 | + /** | |
| 337 | + * Returns a new {@link Condition} instance that is bound to this | |
| 338 | + * {@code Lock} instance. | |
| 339 | + * | |
| 340 | + * <p>Before waiting on the condition the lock must be held by the | |
| 341 | + * current thread. | |
| 342 | + * A call to {@link Condition#await()} will atomically release the lock | |
| 343 | + * before waiting and re-acquire the lock before the wait returns. | |
| 344 | + * | |
| 345 | + * <p><b>Implementation Considerations</b> | |
| 346 | + * | |
| 347 | + * <p>The exact operation of the {@link Condition} instance depends on | |
| 348 | + * the {@code Lock} implementation and must be documented by that | |
| 349 | + * implementation. | |
| 350 | + * | |
| 351 | + * @return A new {@link Condition} instance for this {@code Lock} instance | |
| 352 | + * @throws UnsupportedOperationException if this {@code Lock} | |
| 353 | + * implementation does not support conditions | |
| 354 | + */ | |
| 355 | + Condition newCondition(); | |
| 356 | +} | |
Binary file not shown.
| @@ -0,0 +1,385 @@ | ||
| 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 | +import java.util.concurrent.*; | |
| 38 | +import sun.misc.Unsafe; | |
| 39 | + | |
| 40 | + | |
| 41 | +/** | |
| 42 | + * Basic thread blocking primitives for creating locks and other | |
| 43 | + * synchronization classes. | |
| 44 | + * | |
| 45 | + * <p>This class associates, with each thread that uses it, a permit | |
| 46 | + * (in the sense of the {@link java.util.concurrent.Semaphore | |
| 47 | + * Semaphore} class). A call to {@code park} will return immediately | |
| 48 | + * if the permit is available, consuming it in the process; otherwise | |
| 49 | + * it <em>may</em> block. A call to {@code unpark} makes the permit | |
| 50 | + * available, if it was not already available. (Unlike with Semaphores | |
| 51 | + * though, permits do not accumulate. There is at most one.) | |
| 52 | + * | |
| 53 | + * <p>Methods {@code park} and {@code unpark} provide efficient | |
| 54 | + * means of blocking and unblocking threads that do not encounter the | |
| 55 | + * problems that cause the deprecated methods {@code Thread.suspend} | |
| 56 | + * and {@code Thread.resume} to be unusable for such purposes: Races | |
| 57 | + * between one thread invoking {@code park} and another thread trying | |
| 58 | + * to {@code unpark} it will preserve liveness, due to the | |
| 59 | + * permit. Additionally, {@code park} will return if the caller's | |
| 60 | + * thread was interrupted, and timeout versions are supported. The | |
| 61 | + * {@code park} method may also return at any other time, for "no | |
| 62 | + * reason", so in general must be invoked within a loop that rechecks | |
| 63 | + * conditions upon return. In this sense {@code park} serves as an | |
| 64 | + * optimization of a "busy wait" that does not waste as much time | |
| 65 | + * spinning, but must be paired with an {@code unpark} to be | |
| 66 | + * effective. | |
| 67 | + * | |
| 68 | + * <p>The three forms of {@code park} each also support a | |
| 69 | + * {@code blocker} object parameter. This object is recorded while | |
| 70 | + * the thread is blocked to permit monitoring and diagnostic tools to | |
| 71 | + * identify the reasons that threads are blocked. (Such tools may | |
| 72 | + * access blockers using method {@link #getBlocker}.) The use of these | |
| 73 | + * forms rather than the original forms without this parameter is | |
| 74 | + * strongly encouraged. The normal argument to supply as a | |
| 75 | + * {@code blocker} within a lock implementation is {@code this}. | |
| 76 | + * | |
| 77 | + * <p>These methods are designed to be used as tools for creating | |
| 78 | + * higher-level synchronization utilities, and are not in themselves | |
| 79 | + * useful for most concurrency control applications. The {@code park} | |
| 80 | + * method is designed for use only in constructions of the form: | |
| 81 | + * <pre>while (!canProceed()) { ... LockSupport.park(this); }</pre> | |
| 82 | + * where neither {@code canProceed} nor any other actions prior to the | |
| 83 | + * call to {@code park} entail locking or blocking. Because only one | |
| 84 | + * permit is associated with each thread, any intermediary uses of | |
| 85 | + * {@code park} could interfere with its intended effects. | |
| 86 | + * | |
| 87 | + * <p><b>Sample Usage.</b> Here is a sketch of a first-in-first-out | |
| 88 | + * non-reentrant lock class: | |
| 89 | + * <pre>{@code | |
| 90 | + * class FIFOMutex { | |
| 91 | + * private final AtomicBoolean locked = new AtomicBoolean(false); | |
| 92 | + * private final Queue<Thread> waiters | |
| 93 | + * = new ConcurrentLinkedQueue<Thread>(); | |
| 94 | + * | |
| 95 | + * public void lock() { | |
| 96 | + * boolean wasInterrupted = false; | |
| 97 | + * Thread current = Thread.currentThread(); | |
| 98 | + * waiters.add(current); | |
| 99 | + * | |
| 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() {} // Cannot be instantiated. | |
| 122 | + | |
| 123 | + // Hotspot implementation via intrinsics API | |
| 124 | + private static final Unsafe unsafe = Unsafe.getUnsafe(); | |
| 125 | + private static final long parkBlockerOffset; | |
| 126 | + | |
| 127 | + static { | |
| 128 | + try { | |
| 129 | + parkBlockerOffset = unsafe.objectFieldOffset | |
| 130 | + (java.lang.Thread.class.getDeclaredField("parkBlocker")); | |
| 131 | + } catch (Exception ex) { throw new Error(ex); } | |
| 132 | + } | |
| 133 | + | |
| 134 | + private static void setBlocker(Thread t, Object arg) { | |
| 135 | + // Even though volatile, hotspot doesn't need a write barrier here. | |
| 136 | + unsafe.putObject(t, parkBlockerOffset, arg); | |
| 137 | + } | |
| 138 | + | |
| 139 | + /** | |
| 140 | + * Makes available the permit for the given thread, if it | |
| 141 | + * was not already available. If the thread was blocked on | |
| 142 | + * {@code park} then it will unblock. Otherwise, its next call | |
| 143 | + * to {@code park} is guaranteed not to block. This operation | |
| 144 | + * is not guaranteed to have any effect at all if the given | |
| 145 | + * thread has not been started. | |
| 146 | + * | |
| 147 | + * @param thread the thread to unpark, or {@code null}, in which case | |
| 148 | + * this operation has no effect | |
| 149 | + */ | |
| 150 | + public static void unpark(Thread thread) { | |
| 151 | + if (thread != null) | |
| 152 | + unsafe.unpark(thread); | |
| 153 | + } | |
| 154 | + | |
| 155 | + /** | |
| 156 | + * Disables the current thread for thread scheduling purposes unless the | |
| 157 | + * permit is available. | |
| 158 | + * | |
| 159 | + * <p>If the permit is available then it is consumed and the call returns | |
| 160 | + * immediately; otherwise | |
| 161 | + * the current thread becomes disabled for thread scheduling | |
| 162 | + * purposes and lies dormant until one of three things happens: | |
| 163 | + * | |
| 164 | + * <ul> | |
| 165 | + * <li>Some other thread invokes {@link #unpark unpark} with the | |
| 166 | + * current thread as the target; or | |
| 167 | + * | |
| 168 | + * <li>Some other thread {@linkplain Thread#interrupt interrupts} | |
| 169 | + * the current thread; or | |
| 170 | + * | |
| 171 | + * <li>The call spuriously (that is, for no reason) returns. | |
| 172 | + * </ul> | |
| 173 | + * | |
| 174 | + * <p>This method does <em>not</em> report which of these caused the | |
| 175 | + * method to return. Callers should re-check the conditions which caused | |
| 176 | + * the thread to park in the first place. Callers may also determine, | |
| 177 | + * for example, the interrupt status of the thread upon return. | |
| 178 | + * | |
| 179 | + * @param blocker the synchronization object responsible for this | |
| 180 | + * thread parking | |
| 181 | + * @since 1.6 | |
| 182 | + */ | |
| 183 | + public static void park(Object blocker) { | |
| 184 | + Thread t = Thread.currentThread(); | |
| 185 | + setBlocker(t, blocker); | |
| 186 | + unsafe.park(false, 0L); | |
| 187 | + setBlocker(t, null); | |
| 188 | + } | |
| 189 | + | |
| 190 | + /** | |
| 191 | + * Disables the current thread for thread scheduling purposes, for up to | |
| 192 | + * the specified waiting time, unless the permit is available. | |
| 193 | + * | |
| 194 | + * <p>If the permit is available then it is consumed and the call | |
| 195 | + * returns immediately; otherwise the current thread becomes disabled | |
| 196 | + * for thread scheduling purposes and lies dormant until one of four | |
| 197 | + * things happens: | |
| 198 | + * | |
| 199 | + * <ul> | |
| 200 | + * <li>Some other thread invokes {@link #unpark unpark} with the | |
| 201 | + * current thread as the target; or | |
| 202 | + * | |
| 203 | + * <li>Some other thread {@linkplain Thread#interrupt interrupts} | |
| 204 | + * the current thread; or | |
| 205 | + * | |
| 206 | + * <li>The specified waiting time elapses; or | |
| 207 | + * | |
| 208 | + * <li>The call spuriously (that is, for no reason) returns. | |
| 209 | + * </ul> | |
| 210 | + * | |
| 211 | + * <p>This method does <em>not</em> report which of these caused the | |
| 212 | + * method to return. Callers should re-check the conditions which caused | |
| 213 | + * the thread to park in the first place. Callers may also determine, | |
| 214 | + * for example, the interrupt status of the thread, or the elapsed time | |
| 215 | + * upon return. | |
| 216 | + * | |
| 217 | + * @param blocker the synchronization object responsible for this | |
| 218 | + * thread parking | |
| 219 | + * @param nanos the maximum number of nanoseconds to wait | |
| 220 | + * @since 1.6 | |
| 221 | + */ | |
| 222 | + public static void parkNanos(Object blocker, long nanos) { | |
| 223 | + if (nanos > 0) { | |
| 224 | + Thread t = Thread.currentThread(); | |
| 225 | + setBlocker(t, blocker); | |
| 226 | + unsafe.park(false, nanos); | |
| 227 | + setBlocker(t, null); | |
| 228 | + } | |
| 229 | + } | |
| 230 | + | |
| 231 | + /** | |
| 232 | + * Disables the current thread for thread scheduling purposes, until | |
| 233 | + * the specified deadline, unless the permit is available. | |
| 234 | + * | |
| 235 | + * <p>If the permit is available then it is consumed and the call | |
| 236 | + * returns immediately; otherwise the current thread becomes disabled | |
| 237 | + * for thread scheduling purposes and lies dormant until one of four | |
| 238 | + * things happens: | |
| 239 | + * | |
| 240 | + * <ul> | |
| 241 | + * <li>Some other thread invokes {@link #unpark unpark} with the | |
| 242 | + * current thread as the target; or | |
| 243 | + * | |
| 244 | + * <li>Some other thread {@linkplain Thread#interrupt interrupts} the | |
| 245 | + * current thread; or | |
| 246 | + * | |
| 247 | + * <li>The specified deadline passes; or | |
| 248 | + * | |
| 249 | + * <li>The call spuriously (that is, for no reason) returns. | |
| 250 | + * </ul> | |
| 251 | + * | |
| 252 | + * <p>This method does <em>not</em> report which of these caused the | |
| 253 | + * method to return. Callers should re-check the conditions which caused | |
| 254 | + * the thread to park in the first place. Callers may also determine, | |
| 255 | + * for example, the interrupt status of the thread, or the current time | |
| 256 | + * upon return. | |
| 257 | + * | |
| 258 | + * @param blocker the synchronization object responsible for this | |
| 259 | + * thread parking | |
| 260 | + * @param deadline the absolute time, in milliseconds from the Epoch, | |
| 261 | + * to wait until | |
| 262 | + * @since 1.6 | |
| 263 | + */ | |
| 264 | + public static void parkUntil(Object blocker, long deadline) { | |
| 265 | + Thread t = Thread.currentThread(); | |
| 266 | + setBlocker(t, blocker); | |
| 267 | + unsafe.park(true, deadline); | |
| 268 | + setBlocker(t, null); | |
| 269 | + } | |
| 270 | + | |
| 271 | + /** | |
| 272 | + * Returns the blocker object supplied to the most recent | |
| 273 | + * invocation of a park method that has not yet unblocked, or null | |
| 274 | + * if not blocked. The value returned is just a momentary | |
| 275 | + * snapshot -- the thread may have since unblocked or blocked on a | |
| 276 | + * different blocker object. | |
| 277 | + * | |
| 278 | + * @param t the thread | |
| 279 | + * @return the blocker | |
| 280 | + * @throws NullPointerException if argument is null | |
| 281 | + * @since 1.6 | |
| 282 | + */ | |
| 283 | + public static Object getBlocker(Thread t) { | |
| 284 | + if (t == null) | |
| 285 | + throw new NullPointerException(); | |
| 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 | +} | |
Binary file not shown.
| @@ -0,0 +1,133 @@ | ||
| 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 | + * A <tt>ReadWriteLock</tt> maintains a pair of associated {@link | |
| 40 | + * Lock locks}, one for read-only operations and one for writing. | |
| 41 | + * The {@link #readLock read lock} may be held simultaneously by | |
| 42 | + * multiple reader threads, so long as there are no writers. The | |
| 43 | + * {@link #writeLock write lock} is exclusive. | |
| 44 | + * | |
| 45 | + * <p>All <tt>ReadWriteLock</tt> implementations must guarantee that | |
| 46 | + * the memory synchronization effects of <tt>writeLock</tt> operations | |
| 47 | + * (as specified in the {@link Lock} interface) also hold with respect | |
| 48 | + * to the associated <tt>readLock</tt>. That is, a thread successfully | |
| 49 | + * acquiring the read lock will see all updates made upon previous | |
| 50 | + * release of the write lock. | |
| 51 | + * | |
| 52 | + * <p>A read-write lock allows for a greater level of concurrency in | |
| 53 | + * accessing shared data than that permitted by a mutual exclusion lock. | |
| 54 | + * It exploits the fact that while only a single thread at a time (a | |
| 55 | + * <em>writer</em> thread) can modify the shared data, in many cases any | |
| 56 | + * number of threads can concurrently read the data (hence <em>reader</em> | |
| 57 | + * threads). | |
| 58 | + * In theory, the increase in concurrency permitted by the use of a read-write | |
| 59 | + * lock will lead to performance improvements over the use of a mutual | |
| 60 | + * exclusion lock. In practice this increase in concurrency will only be fully | |
| 61 | + * realized on a multi-processor, and then only if the access patterns for | |
| 62 | + * the shared data are suitable. | |
| 63 | + * | |
| 64 | + * <p>Whether or not a read-write lock will improve performance over the use | |
| 65 | + * of a mutual exclusion lock depends on the frequency that the data is | |
| 66 | + * read compared to being modified, the duration of the read and write | |
| 67 | + * operations, and the contention for the data - that is, the number of | |
| 68 | + * threads that will try to read or write the data at the same time. | |
| 69 | + * For example, a collection that is initially populated with data and | |
| 70 | + * thereafter infrequently modified, while being frequently searched | |
| 71 | + * (such as a directory of some kind) is an ideal candidate for the use of | |
| 72 | + * a read-write lock. However, if updates become frequent then the data | |
| 73 | + * spends most of its time being exclusively locked and there is little, if any | |
| 74 | + * increase in concurrency. Further, if the read operations are too short | |
| 75 | + * the overhead of the read-write lock implementation (which is inherently | |
| 76 | + * more complex than a mutual exclusion lock) can dominate the execution | |
| 77 | + * cost, particularly as many read-write lock implementations still serialize | |
| 78 | + * all threads through a small section of code. Ultimately, only profiling | |
| 79 | + * and measurement will establish whether the use of a read-write lock is | |
| 80 | + * suitable for your application. | |
| 81 | + * | |
| 82 | + * | |
| 83 | + * <p>Although the basic operation of a read-write lock is straight-forward, | |
| 84 | + * there are many policy decisions that an implementation must make, which | |
| 85 | + * may affect the effectiveness of the read-write lock in a given application. | |
| 86 | + * Examples of these policies include: | |
| 87 | + * <ul> | |
| 88 | + * <li>Determining whether to grant the read lock or the write lock, when | |
| 89 | + * both readers and writers are waiting, at the time that a writer releases | |
| 90 | + * the write lock. Writer preference is common, as writes are expected to be | |
| 91 | + * short and infrequent. Reader preference is less common as it can lead to | |
| 92 | + * lengthy delays for a write if the readers are frequent and long-lived as | |
| 93 | + * expected. Fair, or "in-order" implementations are also possible. | |
| 94 | + * | |
| 95 | + * <li>Determining whether readers that request the read lock while a | |
| 96 | + * reader is active and a writer is waiting, are granted the read lock. | |
| 97 | + * Preference to the reader can delay the writer indefinitely, while | |
| 98 | + * preference to the writer can reduce the potential for concurrency. | |
| 99 | + * | |
| 100 | + * <li>Determining whether the locks are reentrant: can a thread with the | |
| 101 | + * write lock reacquire it? Can it acquire a read lock while holding the | |
| 102 | + * write lock? Is the read lock itself reentrant? | |
| 103 | + * | |
| 104 | + * <li>Can the write lock be downgraded to a read lock without allowing | |
| 105 | + * an intervening writer? Can a read lock be upgraded to a write lock, | |
| 106 | + * in preference to other waiting readers or writers? | |
| 107 | + * | |
| 108 | + * </ul> | |
| 109 | + * You should consider all of these things when evaluating the suitability | |
| 110 | + * of a given implementation for your application. | |
| 111 | + * | |
| 112 | + * @see ReentrantReadWriteLock | |
| 113 | + * @see Lock | |
| 114 | + * @see ReentrantLock | |
| 115 | + * | |
| 116 | + * @since 1.5 | |
| 117 | + * @author Doug Lea | |
| 118 | + */ | |
| 119 | +public interface ReadWriteLock { | |
| 120 | + /** | |
| 121 | + * Returns the lock used for reading. | |
| 122 | + * | |
| 123 | + * @return the lock used for reading. | |
| 124 | + */ | |
| 125 | + Lock readLock(); | |
| 126 | + | |
| 127 | + /** | |
| 128 | + * Returns the lock used for writing. | |
| 129 | + * | |
| 130 | + * @return the lock used for writing. | |
| 131 | + */ | |
| 132 | + Lock writeLock(); | |
| 133 | +} | |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
| @@ -0,0 +1,770 @@ | ||
| 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 | +import java.util.*; | |
| 38 | +import java.util.concurrent.*; | |
| 39 | +import java.util.concurrent.atomic.*; | |
| 40 | + | |
| 41 | +/** | |
| 42 | + * A reentrant mutual exclusion {@link Lock} with the same basic | |
| 43 | + * behavior and semantics as the implicit monitor lock accessed using | |
| 44 | + * {@code synchronized} methods and statements, but with extended | |
| 45 | + * capabilities. | |
| 46 | + * | |
| 47 | + * <p>A {@code ReentrantLock} is <em>owned</em> by the thread last | |
| 48 | + * successfully locking, but not yet unlocking it. A thread invoking | |
| 49 | + * {@code lock} will return, successfully acquiring the lock, when | |
| 50 | + * the lock is not owned by another thread. The method will return | |
| 51 | + * immediately if the current thread already owns the lock. This can | |
| 52 | + * be checked using methods {@link #isHeldByCurrentThread}, and {@link | |
| 53 | + * #getHoldCount}. | |
| 54 | + * | |
| 55 | + * <p>The constructor for this class accepts an optional | |
| 56 | + * <em>fairness</em> parameter. When set {@code true}, under | |
| 57 | + * contention, locks favor granting access to the longest-waiting | |
| 58 | + * thread. Otherwise this lock does not guarantee any particular | |
| 59 | + * access order. Programs using fair locks accessed by many threads | |
| 60 | + * may display lower overall throughput (i.e., are slower; often much | |
| 61 | + * slower) than those using the default setting, but have smaller | |
| 62 | + * variances in times to obtain locks and guarantee lack of | |
| 63 | + * starvation. Note however, that fairness of locks does not guarantee | |
| 64 | + * fairness of thread scheduling. Thus, one of many threads using a | |
| 65 | + * fair lock may obtain it multiple times in succession while other | |
| 66 | + * active threads are not progressing and not currently holding the | |
| 67 | + * lock. | |
| 68 | + * Also note that the untimed {@link #tryLock() tryLock} method does not | |
| 69 | + * honor the fairness setting. It will succeed if the lock | |
| 70 | + * is available even if other threads are waiting. | |
| 71 | + * | |
| 72 | + * <p>It is recommended practice to <em>always</em> immediately | |
| 73 | + * follow a call to {@code lock} with a {@code try} block, most | |
| 74 | + * typically in a before/after construction such as: | |
| 75 | + * | |
| 76 | + * <pre> | |
| 77 | + * class X { | |
| 78 | + * private final ReentrantLock lock = new ReentrantLock(); | |
| 79 | + * // ... | |
| 80 | + * | |
| 81 | + * public void m() { | |
| 82 | + * lock.lock(); // block until condition holds | |
| 83 | + * try { | |
| 84 | + * // ... method body | |
| 85 | + * } finally { | |
| 86 | + * lock.unlock() | |
| 87 | + * } | |
| 88 | + * } | |
| 89 | + * } | |
| 90 | + * </pre> | |
| 91 | + * | |
| 92 | + * <p>In addition to implementing the {@link Lock} interface, this | |
| 93 | + * class defines methods {@code isLocked} and | |
| 94 | + * {@code getLockQueueLength}, as well as some associated | |
| 95 | + * {@code protected} access methods that may be useful for | |
| 96 | + * instrumentation and monitoring. | |
| 97 | + * | |
| 98 | + * <p>Serialization of this class behaves in the same way as built-in | |
| 99 | + * locks: a deserialized lock is in the unlocked state, regardless of | |
| 100 | + * its state when serialized. | |
| 101 | + * | |
| 102 | + * <p>This lock supports a maximum of 2147483647 recursive locks by | |
| 103 | + * the same thread. Attempts to exceed this limit result in | |
| 104 | + * {@link Error} throws from locking methods. | |
| 105 | + * | |
| 106 | + * @since 1.5 | |
| 107 | + * @author Doug Lea | |
| 108 | + */ | |
| 109 | +public class ReentrantLock implements Lock, java.io.Serializable { | |
| 110 | + private static final long serialVersionUID = 7373984872572414699L; | |
| 111 | + /** Synchronizer providing all implementation mechanics */ | |
| 112 | + private final Sync sync; | |
| 113 | + | |
| 114 | + /** | |
| 115 | + * Base of synchronization control for this lock. Subclassed | |
| 116 | + * into fair and nonfair versions below. Uses AQS state to | |
| 117 | + * represent the number of holds on the lock. | |
| 118 | + */ | |
| 119 | + abstract static class Sync extends AbstractQueuedSynchronizer { | |
| 120 | + private static final long serialVersionUID = -5179523762034025860L; | |
| 121 | + | |
| 122 | + /** | |
| 123 | + * Performs {@link Lock#lock}. The main reason for subclassing | |
| 124 | + * is to allow fast path for nonfair version. | |
| 125 | + */ | |
| 126 | + abstract void lock(); | |
| 127 | + | |
| 128 | + /** | |
| 129 | + * Performs non-fair tryLock. tryAcquire is | |
| 130 | + * implemented in subclasses, but both need nonfair | |
| 131 | + * try for trylock method. | |
| 132 | + */ | |
| 133 | + final boolean nonfairTryAcquire(int acquires) { | |
| 134 | + final Thread current = Thread.currentThread(); | |
| 135 | + int c = getState(); | |
| 136 | + if (c == 0) { | |
| 137 | + if (compareAndSetState(0, acquires)) { | |
| 138 | + setExclusiveOwnerThread(current); | |
| 139 | + return true; | |
| 140 | + } | |
| 141 | + } | |
| 142 | + else if (current == getExclusiveOwnerThread()) { | |
| 143 | + int nextc = c + acquires; | |
| 144 | + if (nextc < 0) // overflow | |
| 145 | + throw new Error("Maximum lock count exceeded"); | |
| 146 | + setState(nextc); | |
| 147 | + return true; | |
| 148 | + } | |
| 149 | + return false; | |
| 150 | + } | |
| 151 | + | |
| 152 | + protected final boolean tryRelease(int releases) { | |
| 153 | + int c = getState() - releases; | |
| 154 | + if (Thread.currentThread() != getExclusiveOwnerThread()) | |
| 155 | + throw new IllegalMonitorStateException(); | |
| 156 | + boolean free = false; | |
| 157 | + if (c == 0) { | |
| 158 | + free = true; | |
| 159 | + setExclusiveOwnerThread(null); | |
| 160 | + } | |
| 161 | + setState(c); | |
| 162 | + return free; | |
| 163 | + } | |
| 164 | + | |
| 165 | + protected final boolean isHeldExclusively() { | |
| 166 | + // While we must in general read state before owner, | |
| 167 | + // we don't need to do so to check if current thread is owner | |
| 168 | + return getExclusiveOwnerThread() == Thread.currentThread(); | |
| 169 | + } | |
| 170 | + | |
| 171 | + final ConditionObject newCondition() { | |
| 172 | + return new ConditionObject(); | |
| 173 | + } | |
| 174 | + | |
| 175 | + // Methods relayed from outer class | |
| 176 | + | |
| 177 | + final Thread getOwner() { | |
| 178 | + return getState() == 0 ? null : getExclusiveOwnerThread(); | |
| 179 | + } | |
| 180 | + | |
| 181 | + final int getHoldCount() { | |
| 182 | + return isHeldExclusively() ? getState() : 0; | |
| 183 | + } | |
| 184 | + | |
| 185 | + final boolean isLocked() { | |
| 186 | + return getState() != 0; | |
| 187 | + } | |
| 188 | + | |
| 189 | + /** | |
| 190 | + * Reconstitutes this lock instance from a stream. | |
| 191 | + * @param s the stream | |
| 192 | + */ | |
| 193 | + private void readObject(java.io.ObjectInputStream s) | |
| 194 | + throws java.io.IOException, ClassNotFoundException { | |
| 195 | + s.defaultReadObject(); | |
| 196 | + setState(0); // reset to unlocked state | |
| 197 | + } | |
| 198 | + } | |
| 199 | + | |
| 200 | + /** | |
| 201 | + * Sync object for non-fair locks | |
| 202 | + */ | |
| 203 | + static final class NonfairSync extends Sync { | |
| 204 | + private static final long serialVersionUID = 7316153563782823691L; | |
| 205 | + | |
| 206 | + /** | |
| 207 | + * Performs lock. Try immediate barge, backing up to normal | |
| 208 | + * acquire on failure. | |
| 209 | + */ | |
| 210 | + final void lock() { | |
| 211 | + if (compareAndSetState(0, 1)) | |
| 212 | + setExclusiveOwnerThread(Thread.currentThread()); | |
| 213 | + else | |
| 214 | + acquire(1); | |
| 215 | + } | |
| 216 | + | |
| 217 | + protected final boolean tryAcquire(int acquires) { | |
| 218 | + return nonfairTryAcquire(acquires); | |
| 219 | + } | |
| 220 | + } | |
| 221 | + | |
| 222 | + /** | |
| 223 | + * Sync object for fair locks | |
| 224 | + */ | |
| 225 | + static final class FairSync extends Sync { | |
| 226 | + private static final long serialVersionUID = -3000897897090466540L; | |
| 227 | + | |
| 228 | + final void lock() { | |
| 229 | + acquire(1); | |
| 230 | + } | |
| 231 | + | |
| 232 | + /** | |
| 233 | + * Fair version of tryAcquire. Don't grant access unless | |
| 234 | + * recursive call or no waiters or is first. | |
| 235 | + */ | |
| 236 | + protected final boolean tryAcquire(int acquires) { | |
| 237 | + final Thread current = Thread.currentThread(); | |
| 238 | + int c = getState(); | |
| 239 | + if (c == 0) { | |
| 240 | + if (!hasQueuedPredecessors() && | |
| 241 | + compareAndSetState(0, acquires)) { | |
| 242 | + setExclusiveOwnerThread(current); | |
| 243 | + return true; | |
| 244 | + } | |
| 245 | + } | |
| 246 | + else if (current == getExclusiveOwnerThread()) { | |
| 247 | + int nextc = c + acquires; | |
| 248 | + if (nextc < 0) | |
| 249 | + throw new Error("Maximum lock count exceeded"); | |
| 250 | + setState(nextc); | |
| 251 | + return true; | |
| 252 | + } | |
| 253 | + return false; | |
| 254 | + } | |
| 255 | + } | |
| 256 | + | |
| 257 | + /** | |
| 258 | + * Creates an instance of {@code ReentrantLock}. | |
| 259 | + * This is equivalent to using {@code ReentrantLock(false)}. | |
| 260 | + */ | |
| 261 | + public ReentrantLock() { | |
| 262 | + sync = new NonfairSync(); | |
| 263 | + } | |
| 264 | + | |
| 265 | + /** | |
| 266 | + * Creates an instance of {@code ReentrantLock} with the | |
| 267 | + * given fairness policy. | |
| 268 | + * | |
| 269 | + * @param fair {@code true} if this lock should use a fair ordering policy | |
| 270 | + */ | |
| 271 | + public ReentrantLock(boolean fair) { | |
| 272 | + sync = fair ? new FairSync() : new NonfairSync(); | |
| 273 | + } | |
| 274 | + | |
| 275 | + /** | |
| 276 | + * Acquires the lock. | |
| 277 | + * | |
| 278 | + * <p>Acquires the lock if it is not held by another thread and returns | |
| 279 | + * immediately, setting the lock hold count to one. | |
| 280 | + * | |
| 281 | + * <p>If the current thread already holds the lock then the hold | |
| 282 | + * count is incremented by one and the method returns immediately. | |
| 283 | + * | |
| 284 | + * <p>If the lock is held by another thread then the | |
| 285 | + * current thread becomes disabled for thread scheduling | |
| 286 | + * purposes and lies dormant until the lock has been acquired, | |
| 287 | + * at which time the lock hold count is set to one. | |
| 288 | + */ | |
| 289 | + public void lock() { | |
| 290 | + sync.lock(); | |
| 291 | + } | |
| 292 | + | |
| 293 | + /** | |
| 294 | + * Acquires the lock unless the current thread is | |
| 295 | + * {@linkplain Thread#interrupt interrupted}. | |
| 296 | + * | |
| 297 | + * <p>Acquires the lock if it is not held by another thread and returns | |
| 298 | + * immediately, setting the lock hold count to one. | |
| 299 | + * | |
| 300 | + * <p>If the current thread already holds this lock then the hold count | |
| 301 | + * is incremented by one and the method returns immediately. | |
| 302 | + * | |
| 303 | + * <p>If the lock is held by another thread then the | |
| 304 | + * current thread becomes disabled for thread scheduling | |
| 305 | + * purposes and lies dormant until one of two things happens: | |
| 306 | + * | |
| 307 | + * <ul> | |
| 308 | + * | |
| 309 | + * <li>The lock is acquired by the current thread; or | |
| 310 | + * | |
| 311 | + * <li>Some other thread {@linkplain Thread#interrupt interrupts} the | |
| 312 | + * current thread. | |
| 313 | + * | |
| 314 | + * </ul> | |
| 315 | + * | |
| 316 | + * <p>If the lock is acquired by the current thread then the lock hold | |
| 317 | + * count is set to one. | |
| 318 | + * | |
| 319 | + * <p>If the current thread: | |
| 320 | + * | |
| 321 | + * <ul> | |
| 322 | + * | |
| 323 | + * <li>has its interrupted status set on entry to this method; or | |
| 324 | + * | |
| 325 | + * <li>is {@linkplain Thread#interrupt interrupted} while acquiring | |
| 326 | + * the lock, | |
| 327 | + * | |
| 328 | + * </ul> | |
| 329 | + * | |
| 330 | + * then {@link InterruptedException} is thrown and the current thread's | |
| 331 | + * interrupted status is cleared. | |
| 332 | + * | |
| 333 | + * <p>In this implementation, as this method is an explicit | |
| 334 | + * interruption point, preference is given to responding to the | |
| 335 | + * interrupt over normal or reentrant acquisition of the lock. | |
| 336 | + * | |
| 337 | + * @throws InterruptedException if the current thread is interrupted | |
| 338 | + */ | |
| 339 | + public void lockInterruptibly() throws InterruptedException { | |
| 340 | + sync.acquireInterruptibly(1); | |
| 341 | + } | |
| 342 | + | |
| 343 | + /** | |
| 344 | + * Acquires the lock only if it is not held by another thread at the time | |
| 345 | + * of invocation. | |
| 346 | + * | |
| 347 | + * <p>Acquires the lock if it is not held by another thread and | |
| 348 | + * returns immediately with the value {@code true}, setting the | |
| 349 | + * lock hold count to one. Even when this lock has been set to use a | |
| 350 | + * fair ordering policy, a call to {@code tryLock()} <em>will</em> | |
| 351 | + * immediately acquire the lock if it is available, whether or not | |
| 352 | + * other threads are currently waiting for the lock. | |
| 353 | + * This "barging" behavior can be useful in certain | |
| 354 | + * circumstances, even though it breaks fairness. If you want to honor | |
| 355 | + * the fairness setting for this lock, then use | |
| 356 | + * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) } | |
| 357 | + * which is almost equivalent (it also detects interruption). | |
| 358 | + * | |
| 359 | + * <p> If the current thread already holds this lock then the hold | |
| 360 | + * count is incremented by one and the method returns {@code true}. | |
| 361 | + * | |
| 362 | + * <p>If the lock is held by another thread then this method will return | |
| 363 | + * immediately with the value {@code false}. | |
| 364 | + * | |
| 365 | + * @return {@code true} if the lock was free and was acquired by the | |
| 366 | + * current thread, or the lock was already held by the current | |
| 367 | + * thread; and {@code false} otherwise | |
| 368 | + */ | |
| 369 | + public boolean tryLock() { | |
| 370 | + return sync.nonfairTryAcquire(1); | |
| 371 | + } | |
| 372 | + | |
| 373 | + /** | |
| 374 | + * Acquires the lock if it is not held by another thread within the given | |
| 375 | + * waiting time and the current thread has not been | |
| 376 | + * {@linkplain Thread#interrupt interrupted}. | |
| 377 | + * | |
| 378 | + * <p>Acquires the lock if it is not held by another thread and returns | |
| 379 | + * immediately with the value {@code true}, setting the lock hold count | |
| 380 | + * to one. If this lock has been set to use a fair ordering policy then | |
| 381 | + * an available lock <em>will not</em> be acquired if any other threads | |
| 382 | + * are waiting for the lock. This is in contrast to the {@link #tryLock()} | |
| 383 | + * method. If you want a timed {@code tryLock} that does permit barging on | |
| 384 | + * a fair lock then combine the timed and un-timed forms together: | |
| 385 | + * | |
| 386 | + * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... } | |
| 387 | + * </pre> | |
| 388 | + * | |
| 389 | + * <p>If the current thread | |
| 390 | + * already holds this lock then the hold count is incremented by one and | |
| 391 | + * the method returns {@code true}. | |
| 392 | + * | |
| 393 | + * <p>If the lock is held by another thread then the | |
| 394 | + * current thread becomes disabled for thread scheduling | |
| 395 | + * purposes and lies dormant until one of three things happens: | |
| 396 | + * | |
| 397 | + * <ul> | |
| 398 | + * | |
| 399 | + * <li>The lock is acquired by the current thread; or | |
| 400 | + * | |
| 401 | + * <li>Some other thread {@linkplain Thread#interrupt interrupts} | |
| 402 | + * the current thread; or | |
| 403 | + * | |
| 404 | + * <li>The specified waiting time elapses | |
| 405 | + * | |
| 406 | + * </ul> | |
| 407 | + * | |
| 408 | + * <p>If the lock is acquired then the value {@code true} is returned and | |
| 409 | + * the lock hold count is set to one. | |
| 410 | + * | |
| 411 | + * <p>If the current thread: | |
| 412 | + * | |
| 413 | + * <ul> | |
| 414 | + * | |
| 415 | + * <li>has its interrupted status set on entry to this method; or | |
| 416 | + * | |
| 417 | + * <li>is {@linkplain Thread#interrupt interrupted} while | |
| 418 | + * acquiring the lock, | |
| 419 | + * | |
| 420 | + * </ul> | |
| 421 | + * then {@link InterruptedException} is thrown and the current thread's | |
| 422 | + * interrupted status is cleared. | |
| 423 | + * | |
| 424 | + * <p>If the specified waiting time elapses then the value {@code false} | |
| 425 | + * is returned. If the time is less than or equal to zero, the method | |
| 426 | + * will not wait at all. | |
| 427 | + * | |
| 428 | + * <p>In this implementation, as this method is an explicit | |
| 429 | + * interruption point, preference is given to responding to the | |
| 430 | + * interrupt over normal or reentrant acquisition of the lock, and | |
| 431 | + * over reporting the elapse of the waiting time. | |
| 432 | + * | |
| 433 | + * @param timeout the time to wait for the lock | |
| 434 | + * @param unit the time unit of the timeout argument | |
| 435 | + * @return {@code true} if the lock was free and was acquired by the | |
| 436 | + * current thread, or the lock was already held by the current | |
| 437 | + * thread; and {@code false} if the waiting time elapsed before | |
| 438 | + * the lock could be acquired | |
| 439 | + * @throws InterruptedException if the current thread is interrupted | |
| 440 | + * @throws NullPointerException if the time unit is null | |
| 441 | + * | |
| 442 | + */ | |
| 443 | + public boolean tryLock(long timeout, TimeUnit unit) | |
| 444 | + throws InterruptedException { | |
| 445 | + return sync.tryAcquireNanos(1, unit.toNanos(timeout)); | |
| 446 | + } | |
| 447 | + | |
| 448 | + /** | |
| 449 | + * Attempts to release this lock. | |
| 450 | + * | |
| 451 | + * <p>If the current thread is the holder of this lock then the hold | |
| 452 | + * count is decremented. If the hold count is now zero then the lock | |
| 453 | + * is released. If the current thread is not the holder of this | |
| 454 | + * lock then {@link IllegalMonitorStateException} is thrown. | |
| 455 | + * | |
| 456 | + * @throws IllegalMonitorStateException if the current thread does not | |
| 457 | + * hold this lock | |
| 458 | + */ | |
| 459 | + public void unlock() { | |
| 460 | + sync.release(1); | |
| 461 | + } | |
| 462 | + | |
| 463 | + /** | |
| 464 | + * Returns a {@link Condition} instance for use with this | |
| 465 | + * {@link Lock} instance. | |
| 466 | + * | |
| 467 | + * <p>The returned {@link Condition} instance supports the same | |
| 468 | + * usages as do the {@link Object} monitor methods ({@link | |
| 469 | + * Object#wait() wait}, {@link Object#notify notify}, and {@link | |
| 470 | + * Object#notifyAll notifyAll}) when used with the built-in | |
| 471 | + * monitor lock. | |
| 472 | + * | |
| 473 | + * <ul> | |
| 474 | + * | |
| 475 | + * <li>If this lock is not held when any of the {@link Condition} | |
| 476 | + * {@linkplain Condition#await() waiting} or {@linkplain | |
| 477 | + * Condition#signal signalling} methods are called, then an {@link | |
| 478 | + * IllegalMonitorStateException} is thrown. | |
| 479 | + * | |
| 480 | + * <li>When the condition {@linkplain Condition#await() waiting} | |
| 481 | + * methods are called the lock is released and, before they | |
| 482 | + * return, the lock is reacquired and the lock hold count restored | |
| 483 | + * to what it was when the method was called. | |
| 484 | + * | |
| 485 | + * <li>If a thread is {@linkplain Thread#interrupt interrupted} | |
| 486 | + * while waiting then the wait will terminate, an {@link | |
| 487 | + * InterruptedException} will be thrown, and the thread's | |
| 488 | + * interrupted status will be cleared. | |
| 489 | + * | |
| 490 | + * <li> Waiting threads are signalled in FIFO order. | |
| 491 | + * | |
| 492 | + * <li>The ordering of lock reacquisition for threads returning | |
| 493 | + * from waiting methods is the same as for threads initially | |
| 494 | + * acquiring the lock, which is in the default case not specified, | |
| 495 | + * but for <em>fair</em> locks favors those threads that have been | |
| 496 | + * waiting the longest. | |
| 497 | + * | |
| 498 | + * </ul> | |
| 499 | + * | |
| 500 | + * @return the Condition object | |
| 501 | + */ | |
| 502 | + public Condition newCondition() { | |
| 503 | + return sync.newCondition(); | |
| 504 | + } | |
| 505 | + | |
| 506 | + /** | |
| 507 | + * Queries the number of holds on this lock by the current thread. | |
| 508 | + * | |
| 509 | + * <p>A thread has a hold on a lock for each lock action that is not | |
| 510 | + * matched by an unlock action. | |
| 511 | + * | |
| 512 | + * <p>The hold count information is typically only used for testing and | |
| 513 | + * debugging purposes. For example, if a certain section of code should | |
| 514 | + * not be entered with the lock already held then we can assert that | |
| 515 | + * fact: | |
| 516 | + * | |
| 517 | + * <pre> | |
| 518 | + * class X { | |
| 519 | + * ReentrantLock lock = new ReentrantLock(); | |
| 520 | + * // ... | |
| 521 | + * public void m() { | |
| 522 | + * assert lock.getHoldCount() == 0; | |
| 523 | + * lock.lock(); | |
| 524 | + * try { | |
| 525 | + * // ... method body | |
| 526 | + * } finally { | |
| 527 | + * lock.unlock(); | |
| 528 | + * } | |
| 529 | + * } | |
| 530 | + * } | |
| 531 | + * </pre> | |
| 532 | + * | |
| 533 | + * @return the number of holds on this lock by the current thread, | |
| 534 | + * or zero if this lock is not held by the current thread | |
| 535 | + */ | |
| 536 | + public int getHoldCount() { | |
| 537 | + return sync.getHoldCount(); | |
| 538 | + } | |
| 539 | + | |
| 540 | + /** | |
| 541 | + * Queries if this lock is held by the current thread. | |
| 542 | + * | |
| 543 | + * <p>Analogous to the {@link Thread#holdsLock} method for built-in | |
| 544 | + * monitor locks, this method is typically used for debugging and | |
| 545 | + * testing. For example, a method that should only be called while | |
| 546 | + * a lock is held can assert that this is the case: | |
| 547 | + * | |
| 548 | + * <pre> | |
| 549 | + * class X { | |
| 550 | + * ReentrantLock lock = new ReentrantLock(); | |
| 551 | + * // ... | |
| 552 | + * | |
| 553 | + * public void m() { | |
| 554 | + * assert lock.isHeldByCurrentThread(); | |
| 555 | + * // ... method body | |
| 556 | + * } | |
| 557 | + * } | |
| 558 | + * </pre> | |
| 559 | + * | |
| 560 | + * <p>It can also be used to ensure that a reentrant lock is used | |
| 561 | + * in a non-reentrant manner, for example: | |
| 562 | + * | |
| 563 | + * <pre> | |
| 564 | + * class X { | |
| 565 | + * ReentrantLock lock = new ReentrantLock(); | |
| 566 | + * // ... | |
| 567 | + * | |
| 568 | + * public void m() { | |
| 569 | + * assert !lock.isHeldByCurrentThread(); | |
| 570 | + * lock.lock(); | |
| 571 | + * try { | |
| 572 | + * // ... method body | |
| 573 | + * } finally { | |
| 574 | + * lock.unlock(); | |
| 575 | + * } | |
| 576 | + * } | |
| 577 | + * } | |
| 578 | + * </pre> | |
| 579 | + * | |
| 580 | + * @return {@code true} if current thread holds this lock and | |
| 581 | + * {@code false} otherwise | |
| 582 | + */ | |
| 583 | + public boolean isHeldByCurrentThread() { | |
| 584 | + return sync.isHeldExclusively(); | |
| 585 | + } | |
| 586 | + | |
| 587 | + /** | |
| 588 | + * Queries if this lock is held by any thread. This method is | |
| 589 | + * designed for use in monitoring of the system state, | |
| 590 | + * not for synchronization control. | |
| 591 | + * | |
| 592 | + * @return {@code true} if any thread holds this lock and | |
| 593 | + * {@code false} otherwise | |
| 594 | + */ | |
| 595 | + public boolean isLocked() { | |
| 596 | + return sync.isLocked(); | |
| 597 | + } | |
| 598 | + | |
| 599 | + /** | |
| 600 | + * Returns {@code true} if this lock has fairness set true. | |
| 601 | + * | |
| 602 | + * @return {@code true} if this lock has fairness set true | |
| 603 | + */ | |
| 604 | + public final boolean isFair() { | |
| 605 | + return sync instanceof FairSync; | |
| 606 | + } | |
| 607 | + | |
| 608 | + /** | |
| 609 | + * Returns the thread that currently owns this lock, or | |
| 610 | + * {@code null} if not owned. When this method is called by a | |
| 611 | + * thread that is not the owner, the return value reflects a | |
| 612 | + * best-effort approximation of current lock status. For example, | |
| 613 | + * the owner may be momentarily {@code null} even if there are | |
| 614 | + * threads trying to acquire the lock but have not yet done so. | |
| 615 | + * This method is designed to facilitate construction of | |
| 616 | + * subclasses that provide more extensive lock monitoring | |
| 617 | + * facilities. | |
| 618 | + * | |
| 619 | + * @return the owner, or {@code null} if not owned | |
| 620 | + */ | |
| 621 | + protected Thread getOwner() { | |
| 622 | + return sync.getOwner(); | |
| 623 | + } | |
| 624 | + | |
| 625 | + /** | |
| 626 | + * Queries whether any threads are waiting to acquire this lock. Note that | |
| 627 | + * because cancellations may occur at any time, a {@code true} | |
| 628 | + * return does not guarantee that any other thread will ever | |
| 629 | + * acquire this lock. This method is designed primarily for use in | |
| 630 | + * monitoring of the system state. | |
| 631 | + * | |
| 632 | + * @return {@code true} if there may be other threads waiting to | |
| 633 | + * acquire the lock | |
| 634 | + */ | |
| 635 | + public final boolean hasQueuedThreads() { | |
| 636 | + return sync.hasQueuedThreads(); | |
| 637 | + } | |
| 638 | + | |
| 639 | + | |
| 640 | + /** | |
| 641 | + * Queries whether the given thread is waiting to acquire this | |
| 642 | + * lock. Note that because cancellations may occur at any time, a | |
| 643 | + * {@code true} return does not guarantee that this thread | |
| 644 | + * will ever acquire this lock. This method is designed primarily for use | |
| 645 | + * in monitoring of the system state. | |
| 646 | + * | |
| 647 | + * @param thread the thread | |
| 648 | + * @return {@code true} if the given thread is queued waiting for this lock | |
| 649 | + * @throws NullPointerException if the thread is null | |
| 650 | + */ | |
| 651 | + public final boolean hasQueuedThread(Thread thread) { | |
| 652 | + return sync.isQueued(thread); | |
| 653 | + } | |
| 654 | + | |
| 655 | + | |
| 656 | + /** | |
| 657 | + * Returns an estimate of the number of threads waiting to | |
| 658 | + * acquire this lock. The value is only an estimate because the number of | |
| 659 | + * threads may change dynamically while this method traverses | |
| 660 | + * internal data structures. This method is designed for use in | |
| 661 | + * monitoring of the system state, not for synchronization | |
| 662 | + * control. | |
| 663 | + * | |
| 664 | + * @return the estimated number of threads waiting for this lock | |
| 665 | + */ | |
| 666 | + public final int getQueueLength() { | |
| 667 | + return sync.getQueueLength(); | |
| 668 | + } | |
| 669 | + | |
| 670 | + /** | |
| 671 | + * Returns a collection containing threads that may be waiting to | |
| 672 | + * acquire this lock. Because the actual set of threads may change | |
| 673 | + * dynamically while constructing this result, the returned | |
| 674 | + * collection is only a best-effort estimate. The elements of the | |
| 675 | + * returned collection are in no particular order. This method is | |
| 676 | + * designed to facilitate construction of subclasses that provide | |
| 677 | + * more extensive monitoring facilities. | |
| 678 | + * | |
| 679 | + * @return the collection of threads | |
| 680 | + */ | |
| 681 | + protected Collection<Thread> getQueuedThreads() { | |
| 682 | + return sync.getQueuedThreads(); | |
| 683 | + } | |
| 684 | + | |
| 685 | + /** | |
| 686 | + * Queries whether any threads are waiting on the given condition | |
| 687 | + * associated with this lock. Note that because timeouts and | |
| 688 | + * interrupts may occur at any time, a {@code true} return does | |
| 689 | + * not guarantee that a future {@code signal} will awaken any | |
| 690 | + * threads. This method is designed primarily for use in | |
| 691 | + * monitoring of the system state. | |
| 692 | + * | |
| 693 | + * @param condition the condition | |
| 694 | + * @return {@code true} if there are any waiting threads | |
| 695 | + * @throws IllegalMonitorStateException if this lock is not held | |
| 696 | + * @throws IllegalArgumentException if the given condition is | |
| 697 | + * not associated with this lock | |
| 698 | + * @throws NullPointerException if the condition is null | |
| 699 | + */ | |
| 700 | + public boolean hasWaiters(Condition condition) { | |
| 701 | + if (condition == null) | |
| 702 | + throw new NullPointerException(); | |
| 703 | + if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) | |
| 704 | + throw new IllegalArgumentException("not owner"); | |
| 705 | + return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition); | |
| 706 | + } | |
| 707 | + | |
| 708 | + /** | |
| 709 | + * Returns an estimate of the number of threads waiting on the | |
| 710 | + * given condition associated with this lock. Note that because | |
| 711 | + * timeouts and interrupts may occur at any time, the estimate | |
| 712 | + * serves only as an upper bound on the actual number of waiters. | |
| 713 | + * This method is designed for use in monitoring of the system | |
| 714 | + * state, not for synchronization control. | |
| 715 | + * | |
| 716 | + * @param condition the condition | |
| 717 | + * @return the estimated number of waiting threads | |
| 718 | + * @throws IllegalMonitorStateException if this lock is not held | |
| 719 | + * @throws IllegalArgumentException if the given condition is | |
| 720 | + * not associated with this lock | |
| 721 | + * @throws NullPointerException if the condition is null | |
| 722 | + */ | |
| 723 | + public int getWaitQueueLength(Condition condition) { | |
| 724 | + if (condition == null) | |
| 725 | + throw new NullPointerException(); | |
| 726 | + if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) | |
| 727 | + throw new IllegalArgumentException("not owner"); | |
| 728 | + return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition); | |
| 729 | + } | |
| 730 | + | |
| 731 | + /** | |
| 732 | + * Returns a collection containing those threads that may be | |
| 733 | + * waiting on the given condition associated with this lock. | |
| 734 | + * Because the actual set of threads may change dynamically while | |
| 735 | + * constructing this result, the returned collection is only a | |
| 736 | + * best-effort estimate. The elements of the returned collection | |
| 737 | + * are in no particular order. This method is designed to | |
| 738 | + * facilitate construction of subclasses that provide more | |
| 739 | + * extensive condition monitoring facilities. | |
| 740 | + * | |
| 741 | + * @param condition the condition | |
| 742 | + * @return the collection of threads | |
| 743 | + * @throws IllegalMonitorStateException if this lock is not held | |
| 744 | + * @throws IllegalArgumentException if the given condition is | |
| 745 | + * not associated with this lock | |
| 746 | + * @throws NullPointerException if the condition is null | |
| 747 | + */ | |
| 748 | + protected Collection<Thread> getWaitingThreads(Condition condition) { | |
| 749 | + if (condition == null) | |
| 750 | + throw new NullPointerException(); | |
| 751 | + if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) | |
| 752 | + throw new IllegalArgumentException("not owner"); | |
| 753 | + return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition); | |
| 754 | + } | |
| 755 | + | |
| 756 | + /** | |
| 757 | + * Returns a string identifying this lock, as well as its lock state. | |
| 758 | + * The state, in brackets, includes either the String {@code "Unlocked"} | |
| 759 | + * or the String {@code "Locked by"} followed by the | |
| 760 | + * {@linkplain Thread#getName name} of the owning thread. | |
| 761 | + * | |
| 762 | + * @return a string identifying this lock, as well as its lock state | |
| 763 | + */ | |
| 764 | + public String toString() { | |
| 765 | + Thread o = sync.getOwner(); | |
| 766 | + return super.toString() + ((o == null) ? | |
| 767 | + "[Unlocked]" : | |
| 768 | + "[Locked by thread " + o.getName() + "]"); | |
| 769 | + } | |
| 770 | +} | |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
| @@ -0,0 +1,1486 @@ | ||
| 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 | +import java.util.concurrent.*; | |
| 38 | +import java.util.concurrent.atomic.*; | |
| 39 | +import java.util.*; | |
| 40 | + | |
| 41 | +/** | |
| 42 | + * An implementation of {@link ReadWriteLock} supporting similar | |
| 43 | + * semantics to {@link ReentrantLock}. | |
| 44 | + * <p>This class has the following properties: | |
| 45 | + * | |
| 46 | + * <ul> | |
| 47 | + * <li><b>Acquisition order</b> | |
| 48 | + * | |
| 49 | + * <p> This class does not impose a reader or writer preference | |
| 50 | + * ordering for lock access. However, it does support an optional | |
| 51 | + * <em>fairness</em> policy. | |
| 52 | + * | |
| 53 | + * <dl> | |
| 54 | + * <dt><b><i>Non-fair mode (default)</i></b> | |
| 55 | + * <dd>When constructed as non-fair (the default), the order of entry | |
| 56 | + * to the read and write lock is unspecified, subject to reentrancy | |
| 57 | + * constraints. A nonfair lock that is continuously contended may | |
| 58 | + * indefinitely postpone one or more reader or writer threads, but | |
| 59 | + * will normally have higher throughput than a fair lock. | |
| 60 | + * <p> | |
| 61 | + * | |
| 62 | + * <dt><b><i>Fair mode</i></b> | |
| 63 | + * <dd> When constructed as fair, threads contend for entry using an | |
| 64 | + * approximately arrival-order policy. When the currently held lock | |
| 65 | + * is released either the longest-waiting single writer thread will | |
| 66 | + * be assigned the write lock, or if there is a group of reader threads | |
| 67 | + * waiting longer than all waiting writer threads, that group will be | |
| 68 | + * assigned the read lock. | |
| 69 | + * | |
| 70 | + * <p>A thread that tries to acquire a fair read lock (non-reentrantly) | |
| 71 | + * will block if either the write lock is held, or there is a waiting | |
| 72 | + * writer thread. The thread will not acquire the read lock until | |
| 73 | + * after the oldest currently waiting writer thread has acquired and | |
| 74 | + * released the write lock. Of course, if a waiting writer abandons | |
| 75 | + * its wait, leaving one or more reader threads as the longest waiters | |
| 76 | + * in the queue with the write lock free, then those readers will be | |
| 77 | + * assigned the read lock. | |
| 78 | + * | |
| 79 | + * <p>A thread that tries to acquire a fair write lock (non-reentrantly) | |
| 80 | + * will block unless both the read lock and write lock are free (which | |
| 81 | + * implies there are no waiting threads). (Note that the non-blocking | |
| 82 | + * {@link ReadLock#tryLock()} and {@link WriteLock#tryLock()} methods | |
| 83 | + * do not honor this fair setting and will acquire the lock if it is | |
| 84 | + * possible, regardless of waiting threads.) | |
| 85 | + * <p> | |
| 86 | + * </dl> | |
| 87 | + * | |
| 88 | + * <li><b>Reentrancy</b> | |
| 89 | + * | |
| 90 | + * <p>This lock allows both readers and writers to reacquire read or | |
| 91 | + * write locks in the style of a {@link ReentrantLock}. Non-reentrant | |
| 92 | + * readers are not allowed until all write locks held by the writing | |
| 93 | + * thread have been released. | |
| 94 | + * | |
| 95 | + * <p>Additionally, a writer can acquire the read lock, but not | |
| 96 | + * vice-versa. Among other applications, reentrancy can be useful | |
| 97 | + * when write locks are held during calls or callbacks to methods that | |
| 98 | + * perform reads under read locks. If a reader tries to acquire the | |
| 99 | + * write lock it will never succeed. | |
| 100 | + * | |
| 101 | + * <li><b>Lock downgrading</b> | |
| 102 | + * <p>Reentrancy also allows downgrading from the write lock to a read lock, | |
| 103 | + * by acquiring the write lock, then the read lock and then releasing the | |
| 104 | + * write lock. However, upgrading from a read lock to the write lock is | |
| 105 | + * <b>not</b> possible. | |
| 106 | + * | |
| 107 | + * <li><b>Interruption of lock acquisition</b> | |
| 108 | + * <p>The read lock and write lock both support interruption during lock | |
| 109 | + * acquisition. | |
| 110 | + * | |
| 111 | + * <li><b>{@link Condition} support</b> | |
| 112 | + * <p>The write lock provides a {@link Condition} implementation that | |
| 113 | + * behaves in the same way, with respect to the write lock, as the | |
| 114 | + * {@link Condition} implementation provided by | |
| 115 | + * {@link ReentrantLock#newCondition} does for {@link ReentrantLock}. | |
| 116 | + * This {@link Condition} can, of course, only be used with the write lock. | |
| 117 | + * | |
| 118 | + * <p>The read lock does not support a {@link Condition} and | |
| 119 | + * {@code readLock().newCondition()} throws | |
| 120 | + * {@code UnsupportedOperationException}. | |
| 121 | + * | |
| 122 | + * <li><b>Instrumentation</b> | |
| 123 | + * <p>This class supports methods to determine whether locks | |
| 124 | + * are held or contended. These methods are designed for monitoring | |
| 125 | + * system state, not for synchronization control. | |
| 126 | + * </ul> | |
| 127 | + * | |
| 128 | + * <p>Serialization of this class behaves in the same way as built-in | |
| 129 | + * locks: a deserialized lock is in the unlocked state, regardless of | |
| 130 | + * its state when serialized. | |
| 131 | + * | |
| 132 | + * <p><b>Sample usages</b>. Here is a code sketch showing how to perform | |
| 133 | + * lock downgrading after updating a cache (exception handling is | |
| 134 | + * particularly tricky when handling multiple locks in a non-nested | |
| 135 | + * fashion): | |
| 136 | + * | |
| 137 | + * <pre> {@code | |
| 138 | + * class CachedData { | |
| 139 | + * Object data; | |
| 140 | + * volatile boolean cacheValid; | |
| 141 | + * final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); | |
| 142 | + * | |
| 143 | + * void processCachedData() { | |
| 144 | + * rwl.readLock().lock(); | |
| 145 | + * if (!cacheValid) { | |
| 146 | + * // Must release read lock before acquiring write lock | |
| 147 | + * rwl.readLock().unlock(); | |
| 148 | + * rwl.writeLock().lock(); | |
| 149 | + * try { | |
| 150 | + * // Recheck state because another thread might have | |
| 151 | + * // acquired write lock and changed state before we did. | |
| 152 | + * if (!cacheValid) { | |
| 153 | + * data = ... | |
| 154 | + * cacheValid = true; | |
| 155 | + * } | |
| 156 | + * // Downgrade by acquiring read lock before releasing write lock | |
| 157 | + * rwl.readLock().lock(); | |
| 158 | + * } finally { | |
| 159 | + * rwl.writeLock().unlock(); // Unlock write, still hold read | |
| 160 | + * } | |
| 161 | + * } | |
| 162 | + * | |
| 163 | + * try { | |
| 164 | + * use(data); | |
| 165 | + * } finally { | |
| 166 | + * rwl.readLock().unlock(); | |
| 167 | + * } | |
| 168 | + * } | |
| 169 | + * }}</pre> | |
| 170 | + * | |
| 171 | + * ReentrantReadWriteLocks can be used to improve concurrency in some | |
| 172 | + * uses of some kinds of Collections. This is typically worthwhile | |
| 173 | + * only when the collections are expected to be large, accessed by | |
| 174 | + * more reader threads than writer threads, and entail operations with | |
| 175 | + * overhead that outweighs synchronization overhead. For example, here | |
| 176 | + * is a class using a TreeMap that is expected to be large and | |
| 177 | + * concurrently accessed. | |
| 178 | + * | |
| 179 | + * <pre>{@code | |
| 180 | + * class RWDictionary { | |
| 181 | + * private final Map<String, Data> m = new TreeMap<String, Data>(); | |
| 182 | + * private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); | |
| 183 | + * private final Lock r = rwl.readLock(); | |
| 184 | + * private final Lock w = rwl.writeLock(); | |
| 185 | + * | |
| 186 | + * public Data get(String key) { | |
| 187 | + * r.lock(); | |
| 188 | + * try { return m.get(key); } | |
| 189 | + * finally { r.unlock(); } | |
| 190 | + * } | |
| 191 | + * public String[] allKeys() { | |
| 192 | + * r.lock(); | |
| 193 | + * try { return m.keySet().toArray(); } | |
| 194 | + * finally { r.unlock(); } | |
| 195 | + * } | |
| 196 | + * public Data put(String key, Data value) { | |
| 197 | + * w.lock(); | |
| 198 | + * try { return m.put(key, value); } | |
| 199 | + * finally { w.unlock(); } | |
| 200 | + * } | |
| 201 | + * public void clear() { | |
| 202 | + * w.lock(); | |
| 203 | + * try { m.clear(); } | |
| 204 | + * finally { w.unlock(); } | |
| 205 | + * } | |
| 206 | + * }}</pre> | |
| 207 | + * | |
| 208 | + * <h3>Implementation Notes</h3> | |
| 209 | + * | |
| 210 | + * <p>This lock supports a maximum of 65535 recursive write locks | |
| 211 | + * and 65535 read locks. Attempts to exceed these limits result in | |
| 212 | + * {@link Error} throws from locking methods. | |
| 213 | + * | |
| 214 | + * @since 1.5 | |
| 215 | + * @author Doug Lea | |
| 216 | + * | |
| 217 | + */ | |
| 218 | +public class ReentrantReadWriteLock | |
| 219 | + implements ReadWriteLock, java.io.Serializable { | |
| 220 | + private static final long serialVersionUID = -6992448646407690164L; | |
| 221 | + /** Inner class providing readlock */ | |
| 222 | + private final ReentrantReadWriteLock.ReadLock readerLock; | |
| 223 | + /** Inner class providing writelock */ | |
| 224 | + private final ReentrantReadWriteLock.WriteLock writerLock; | |
| 225 | + /** Performs all synchronization mechanics */ | |
| 226 | + final Sync sync; | |
| 227 | + | |
| 228 | + /** | |
| 229 | + * Creates a new {@code ReentrantReadWriteLock} with | |
| 230 | + * default (nonfair) ordering properties. | |
| 231 | + */ | |
| 232 | + public ReentrantReadWriteLock() { | |
| 233 | + this(false); | |
| 234 | + } | |
| 235 | + | |
| 236 | + /** | |
| 237 | + * Creates a new {@code ReentrantReadWriteLock} with | |
| 238 | + * the given fairness policy. | |
| 239 | + * | |
| 240 | + * @param fair {@code true} if this lock should use a fair ordering policy | |
| 241 | + */ | |
| 242 | + public ReentrantReadWriteLock(boolean fair) { | |
| 243 | + sync = fair ? new FairSync() : new NonfairSync(); | |
| 244 | + readerLock = new ReadLock(this); | |
| 245 | + writerLock = new WriteLock(this); | |
| 246 | + } | |
| 247 | + | |
| 248 | + public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; } | |
| 249 | + public ReentrantReadWriteLock.ReadLock readLock() { return readerLock; } | |
| 250 | + | |
| 251 | + /** | |
| 252 | + * Synchronization implementation for ReentrantReadWriteLock. | |
| 253 | + * Subclassed into fair and nonfair versions. | |
| 254 | + */ | |
| 255 | + abstract static class Sync extends AbstractQueuedSynchronizer { | |
| 256 | + private static final long serialVersionUID = 6317671515068378041L; | |
| 257 | + | |
| 258 | + /* | |
| 259 | + * Read vs write count extraction constants and functions. | |
| 260 | + * Lock state is logically divided into two unsigned shorts: | |
| 261 | + * The lower one representing the exclusive (writer) lock hold count, | |
| 262 | + * and the upper the shared (reader) hold count. | |
| 263 | + */ | |
| 264 | + | |
| 265 | + static final int SHARED_SHIFT = 16; | |
| 266 | + static final int SHARED_UNIT = (1 << SHARED_SHIFT); | |
| 267 | + static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1; | |
| 268 | + static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1; | |
| 269 | + | |
| 270 | + /** Returns the number of shared holds represented in count */ | |
| 271 | + static int sharedCount(int c) { return c >>> SHARED_SHIFT; } | |
| 272 | + /** Returns the number of exclusive holds represented in count */ | |
| 273 | + static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; } | |
| 274 | + | |
| 275 | + /** | |
| 276 | + * A counter for per-thread read hold counts. | |
| 277 | + * Maintained as a ThreadLocal; cached in cachedHoldCounter | |
| 278 | + */ | |
| 279 | + static final class HoldCounter { | |
| 280 | + int count = 0; | |
| 281 | + // Use id, not reference, to avoid garbage retention | |
| 282 | + final long tid = Thread.currentThread().getId(); | |
| 283 | + } | |
| 284 | + | |
| 285 | + /** | |
| 286 | + * ThreadLocal subclass. Easiest to explicitly define for sake | |
| 287 | + * of deserialization mechanics. | |
| 288 | + */ | |
| 289 | + static final class ThreadLocalHoldCounter | |
| 290 | + extends ThreadLocal<HoldCounter> { | |
| 291 | + public HoldCounter initialValue() { | |
| 292 | + return new HoldCounter(); | |
| 293 | + } | |
| 294 | + } | |
| 295 | + | |
| 296 | + /** | |
| 297 | + * The number of reentrant read locks held by current thread. | |
| 298 | + * Initialized only in constructor and readObject. | |
| 299 | + * Removed whenever a thread's read hold count drops to 0. | |
| 300 | + */ | |
| 301 | + private transient ThreadLocalHoldCounter readHolds; | |
| 302 | + | |
| 303 | + /** | |
| 304 | + * The hold count of the last thread to successfully acquire | |
| 305 | + * readLock. This saves ThreadLocal lookup in the common case | |
| 306 | + * where the next thread to release is the last one to | |
| 307 | + * acquire. This is non-volatile since it is just used | |
| 308 | + * as a heuristic, and would be great for threads to cache. | |
| 309 | + * | |
| 310 | + * <p>Can outlive the Thread for which it is caching the read | |
| 311 | + * hold count, but avoids garbage retention by not retaining a | |
| 312 | + * reference to the Thread. | |
| 313 | + * | |
| 314 | + * <p>Accessed via a benign data race; relies on the memory | |
| 315 | + * model's final field and out-of-thin-air guarantees. | |
| 316 | + */ | |
| 317 | + private transient HoldCounter cachedHoldCounter; | |
| 318 | + | |
| 319 | + /** | |
| 320 | + * firstReader is the first thread to have acquired the read lock. | |
| 321 | + * firstReaderHoldCount is firstReader's hold count. | |
| 322 | + * | |
| 323 | + * <p>More precisely, firstReader is the unique thread that last | |
| 324 | + * changed the shared count from 0 to 1, and has not released the | |
| 325 | + * read lock since then; null if there is no such thread. | |
| 326 | + * | |
| 327 | + * <p>Cannot cause garbage retention unless the thread terminated | |
| 328 | + * without relinquishing its read locks, since tryReleaseShared | |
| 329 | + * sets it to null. | |
| 330 | + * | |
| 331 | + * <p>Accessed via a benign data race; relies on the memory | |
| 332 | + * model's out-of-thin-air guarantees for references. | |
| 333 | + * | |
| 334 | + * <p>This allows tracking of read holds for uncontended read | |
| 335 | + * locks to be very cheap. | |
| 336 | + */ | |
| 337 | + private transient Thread firstReader = null; | |
| 338 | + private transient int firstReaderHoldCount; | |
| 339 | + | |
| 340 | + Sync() { | |
| 341 | + readHolds = new ThreadLocalHoldCounter(); | |
| 342 | + setState(getState()); // ensures visibility of readHolds | |
| 343 | + } | |
| 344 | + | |
| 345 | + /* | |
| 346 | + * Acquires and releases use the same code for fair and | |
| 347 | + * nonfair locks, but differ in whether/how they allow barging | |
| 348 | + * when queues are non-empty. | |
| 349 | + */ | |
| 350 | + | |
| 351 | + /** | |
| 352 | + * Returns true if the current thread, when trying to acquire | |
| 353 | + * the read lock, and otherwise eligible to do so, should block | |
| 354 | + * because of policy for overtaking other waiting threads. | |
| 355 | + */ | |
| 356 | + abstract boolean readerShouldBlock(); | |
| 357 | + | |
| 358 | + /** | |
| 359 | + * Returns true if the current thread, when trying to acquire | |
| 360 | + * the write lock, and otherwise eligible to do so, should block | |
| 361 | + * because of policy for overtaking other waiting threads. | |
| 362 | + */ | |
| 363 | + abstract boolean writerShouldBlock(); | |
| 364 | + | |
| 365 | + /* | |
| 366 | + * Note that tryRelease and tryAcquire can be called by | |
| 367 | + * Conditions. So it is possible that their arguments contain | |
| 368 | + * both read and write holds that are all released during a | |
| 369 | + * condition wait and re-established in tryAcquire. | |
| 370 | + */ | |
| 371 | + | |
| 372 | + protected final boolean tryRelease(int releases) { | |
| 373 | + if (!isHeldExclusively()) | |
| 374 | + throw new IllegalMonitorStateException(); | |
| 375 | + int nextc = getState() - releases; | |
| 376 | + boolean free = exclusiveCount(nextc) == 0; | |
| 377 | + if (free) | |
| 378 | + setExclusiveOwnerThread(null); | |
| 379 | + setState(nextc); | |
| 380 | + return free; | |
| 381 | + } | |
| 382 | + | |
| 383 | + protected final boolean tryAcquire(int acquires) { | |
| 384 | + /* | |
| 385 | + * Walkthrough: | |
| 386 | + * 1. If read count nonzero or write count nonzero | |
| 387 | + * and owner is a different thread, fail. | |
| 388 | + * 2. If count would saturate, fail. (This can only | |
| 389 | + * happen if count is already nonzero.) | |
| 390 | + * 3. Otherwise, this thread is eligible for lock if | |
| 391 | + * it is either a reentrant acquire or | |
| 392 | + * queue policy allows it. If so, update state | |
| 393 | + * and set owner. | |
| 394 | + */ | |
| 395 | + Thread current = Thread.currentThread(); | |
| 396 | + int c = getState(); | |
| 397 | + int w = exclusiveCount(c); | |
| 398 | + if (c != 0) { | |
| 399 | + // (Note: if c != 0 and w == 0 then shared count != 0) | |
| 400 | + if (w == 0 || current != getExclusiveOwnerThread()) | |
| 401 | + return false; | |
| 402 | + if (w + exclusiveCount(acquires) > MAX_COUNT) | |
| 403 | + throw new Error("Maximum lock count exceeded"); | |
| 404 | + // Reentrant acquire | |
| 405 | + setState(c + acquires); | |
| 406 | + return true; | |
| 407 | + } | |
| 408 | + if (writerShouldBlock() || | |
| 409 | + !compareAndSetState(c, c + acquires)) | |
| 410 | + return false; | |
| 411 | + setExclusiveOwnerThread(current); | |
| 412 | + return true; | |
| 413 | + } | |
| 414 | + | |
| 415 | + protected final boolean tryReleaseShared(int unused) { | |
| 416 | + Thread current = Thread.currentThread(); | |
| 417 | + if (firstReader == current) { | |
| 418 | + // assert firstReaderHoldCount > 0; | |
| 419 | + if (firstReaderHoldCount == 1) | |
| 420 | + firstReader = null; | |
| 421 | + else | |
| 422 | + firstReaderHoldCount--; | |
| 423 | + } else { | |
| 424 | + HoldCounter rh = cachedHoldCounter; | |
| 425 | + if (rh == null || rh.tid != current.getId()) | |
| 426 | + rh = readHolds.get(); | |
| 427 | + int count = rh.count; | |
| 428 | + if (count <= 1) { | |
| 429 | + readHolds.remove(); | |
| 430 | + if (count <= 0) | |
| 431 | + throw unmatchedUnlockException(); | |
| 432 | + } | |
| 433 | + --rh.count; | |
| 434 | + } | |
| 435 | + for (;;) { | |
| 436 | + int c = getState(); | |
| 437 | + int nextc = c - SHARED_UNIT; | |
| 438 | + if (compareAndSetState(c, nextc)) | |
| 439 | + // Releasing the read lock has no effect on readers, | |
| 440 | + // but it may allow waiting writers to proceed if | |
| 441 | + // both read and write locks are now free. | |
| 442 | + return nextc == 0; | |
| 443 | + } | |
| 444 | + } | |
| 445 | + | |
| 446 | + private IllegalMonitorStateException unmatchedUnlockException() { | |
| 447 | + return new IllegalMonitorStateException( | |
| 448 | + "attempt to unlock read lock, not locked by current thread"); | |
| 449 | + } | |
| 450 | + | |
| 451 | + protected final int tryAcquireShared(int unused) { | |
| 452 | + /* | |
| 453 | + * Walkthrough: | |
| 454 | + * 1. If write lock held by another thread, fail. | |
| 455 | + * 2. Otherwise, this thread is eligible for | |
| 456 | + * lock wrt state, so ask if it should block | |
| 457 | + * because of queue policy. If not, try | |
| 458 | + * to grant by CASing state and updating count. | |
| 459 | + * Note that step does not check for reentrant | |
| 460 | + * acquires, which is postponed to full version | |
| 461 | + * to avoid having to check hold count in | |
| 462 | + * the more typical non-reentrant case. | |
| 463 | + * 3. If step 2 fails either because thread | |
| 464 | + * apparently not eligible or CAS fails or count | |
| 465 | + * saturated, chain to version with full retry loop. | |
| 466 | + */ | |
| 467 | + Thread current = Thread.currentThread(); | |
| 468 | + int c = getState(); | |
| 469 | + if (exclusiveCount(c) != 0 && | |
| 470 | + getExclusiveOwnerThread() != current) | |
| 471 | + return -1; | |
| 472 | + int r = sharedCount(c); | |
| 473 | + if (!readerShouldBlock() && | |
| 474 | + r < MAX_COUNT && | |
| 475 | + compareAndSetState(c, c + SHARED_UNIT)) { | |
| 476 | + if (r == 0) { | |
| 477 | + firstReader = current; | |
| 478 | + firstReaderHoldCount = 1; | |
| 479 | + } else if (firstReader == current) { | |
| 480 | + firstReaderHoldCount++; | |
| 481 | + } else { | |
| 482 | + HoldCounter rh = cachedHoldCounter; | |
| 483 | + if (rh == null || rh.tid != current.getId()) | |
| 484 | + cachedHoldCounter = rh = readHolds.get(); | |
| 485 | + else if (rh.count == 0) | |
| 486 | + readHolds.set(rh); | |
| 487 | + rh.count++; | |
| 488 | + } | |
| 489 | + return 1; | |
| 490 | + } | |
| 491 | + return fullTryAcquireShared(current); | |
| 492 | + } | |
| 493 | + | |
| 494 | + /** | |
| 495 | + * Full version of acquire for reads, that handles CAS misses | |
| 496 | + * and reentrant reads not dealt with in tryAcquireShared. | |
| 497 | + */ | |
| 498 | + final int fullTryAcquireShared(Thread current) { | |
| 499 | + /* | |
| 500 | + * This code is in part redundant with that in | |
| 501 | + * tryAcquireShared but is simpler overall by not | |
| 502 | + * complicating tryAcquireShared with interactions between | |
| 503 | + * retries and lazily reading hold counts. | |
| 504 | + */ | |
| 505 | + HoldCounter rh = null; | |
| 506 | + for (;;) { | |
| 507 | + int c = getState(); | |
| 508 | + if (exclusiveCount(c) != 0) { | |
| 509 | + if (getExclusiveOwnerThread() != current) | |
| 510 | + return -1; | |
| 511 | + // else we hold the exclusive lock; blocking here | |
| 512 | + // would cause deadlock. | |
| 513 | + } else if (readerShouldBlock()) { | |
| 514 | + // Make sure we're not acquiring read lock reentrantly | |
| 515 | + if (firstReader == current) { | |
| 516 | + // assert firstReaderHoldCount > 0; | |
| 517 | + } else { | |
| 518 | + if (rh == null) { | |
| 519 | + rh = cachedHoldCounter; | |
| 520 | + if (rh == null || rh.tid != current.getId()) { | |
| 521 | + rh = readHolds.get(); | |
| 522 | + if (rh.count == 0) | |
| 523 | + readHolds.remove(); | |
| 524 | + } | |
| 525 | + } | |
| 526 | + if (rh.count == 0) | |
| 527 | + return -1; | |
| 528 | + } | |
| 529 | + } | |
| 530 | + if (sharedCount(c) == MAX_COUNT) | |
| 531 | + throw new Error("Maximum lock count exceeded"); | |
| 532 | + if (compareAndSetState(c, c + SHARED_UNIT)) { | |
| 533 | + if (sharedCount(c) == 0) { | |
| 534 | + firstReader = current; | |
| 535 | + firstReaderHoldCount = 1; | |
| 536 | + } else if (firstReader == current) { | |
| 537 | + firstReaderHoldCount++; | |
| 538 | + } else { | |
| 539 | + if (rh == null) | |
| 540 | + rh = cachedHoldCounter; | |
| 541 | + if (rh == null || rh.tid != current.getId()) | |
| 542 | + rh = readHolds.get(); | |
| 543 | + else if (rh.count == 0) | |
| 544 | + readHolds.set(rh); | |
| 545 | + rh.count++; | |
| 546 | + cachedHoldCounter = rh; // cache for release | |
| 547 | + } | |
| 548 | + return 1; | |
| 549 | + } | |
| 550 | + } | |
| 551 | + } | |
| 552 | + | |
| 553 | + /** | |
| 554 | + * Performs tryLock for write, enabling barging in both modes. | |
| 555 | + * This is identical in effect to tryAcquire except for lack | |
| 556 | + * of calls to writerShouldBlock. | |
| 557 | + */ | |
| 558 | + final boolean tryWriteLock() { | |
| 559 | + Thread current = Thread.currentThread(); | |
| 560 | + int c = getState(); | |
| 561 | + if (c != 0) { | |
| 562 | + int w = exclusiveCount(c); | |
| 563 | + if (w == 0 || current != getExclusiveOwnerThread()) | |
| 564 | + return false; | |
| 565 | + if (w == MAX_COUNT) | |
| 566 | + throw new Error("Maximum lock count exceeded"); | |
| 567 | + } | |
| 568 | + if (!compareAndSetState(c, c + 1)) | |
| 569 | + return false; | |
| 570 | + setExclusiveOwnerThread(current); | |
| 571 | + return true; | |
| 572 | + } | |
| 573 | + | |
| 574 | + /** | |
| 575 | + * Performs tryLock for read, enabling barging in both modes. | |
| 576 | + * This is identical in effect to tryAcquireShared except for | |
| 577 | + * lack of calls to readerShouldBlock. | |
| 578 | + */ | |
| 579 | + final boolean tryReadLock() { | |
| 580 | + Thread current = Thread.currentThread(); | |
| 581 | + for (;;) { | |
| 582 | + int c = getState(); | |
| 583 | + if (exclusiveCount(c) != 0 && | |
| 584 | + getExclusiveOwnerThread() != current) | |
| 585 | + return false; | |
| 586 | + int r = sharedCount(c); | |
| 587 | + if (r == MAX_COUNT) | |
| 588 | + throw new Error("Maximum lock count exceeded"); | |
| 589 | + if (compareAndSetState(c, c + SHARED_UNIT)) { | |
| 590 | + if (r == 0) { | |
| 591 | + firstReader = current; | |
| 592 | + firstReaderHoldCount = 1; | |
| 593 | + } else if (firstReader == current) { | |
| 594 | + firstReaderHoldCount++; | |
| 595 | + } else { | |
| 596 | + HoldCounter rh = cachedHoldCounter; | |
| 597 | + if (rh == null || rh.tid != current.getId()) | |
| 598 | + cachedHoldCounter = rh = readHolds.get(); | |
| 599 | + else if (rh.count == 0) | |
| 600 | + readHolds.set(rh); | |
| 601 | + rh.count++; | |
| 602 | + } | |
| 603 | + return true; | |
| 604 | + } | |
| 605 | + } | |
| 606 | + } | |
| 607 | + | |
| 608 | + protected final boolean isHeldExclusively() { | |
| 609 | + // While we must in general read state before owner, | |
| 610 | + // we don't need to do so to check if current thread is owner | |
| 611 | + return getExclusiveOwnerThread() == Thread.currentThread(); | |
| 612 | + } | |
| 613 | + | |
| 614 | + // Methods relayed to outer class | |
| 615 | + | |
| 616 | + final ConditionObject newCondition() { | |
| 617 | + return new ConditionObject(); | |
| 618 | + } | |
| 619 | + | |
| 620 | + final Thread getOwner() { | |
| 621 | + // Must read state before owner to ensure memory consistency | |
| 622 | + return ((exclusiveCount(getState()) == 0) ? | |
| 623 | + null : | |
| 624 | + getExclusiveOwnerThread()); | |
| 625 | + } | |
| 626 | + | |
| 627 | + final int getReadLockCount() { | |
| 628 | + return sharedCount(getState()); | |
| 629 | + } | |
| 630 | + | |
| 631 | + final boolean isWriteLocked() { | |
| 632 | + return exclusiveCount(getState()) != 0; | |
| 633 | + } | |
| 634 | + | |
| 635 | + final int getWriteHoldCount() { | |
| 636 | + return isHeldExclusively() ? exclusiveCount(getState()) : 0; | |
| 637 | + } | |
| 638 | + | |
| 639 | + final int getReadHoldCount() { | |
| 640 | + if (getReadLockCount() == 0) | |
| 641 | + return 0; | |
| 642 | + | |
| 643 | + Thread current = Thread.currentThread(); | |
| 644 | + if (firstReader == current) | |
| 645 | + return firstReaderHoldCount; | |
| 646 | + | |
| 647 | + HoldCounter rh = cachedHoldCounter; | |
| 648 | + if (rh != null && rh.tid == current.getId()) | |
| 649 | + return rh.count; | |
| 650 | + | |
| 651 | + int count = readHolds.get().count; | |
| 652 | + if (count == 0) readHolds.remove(); | |
| 653 | + return count; | |
| 654 | + } | |
| 655 | + | |
| 656 | + /** | |
| 657 | + * Reconstitute this lock instance from a stream | |
| 658 | + * @param s the stream | |
| 659 | + */ | |
| 660 | + private void readObject(java.io.ObjectInputStream s) | |
| 661 | + throws java.io.IOException, ClassNotFoundException { | |
| 662 | + s.defaultReadObject(); | |
| 663 | + readHolds = new ThreadLocalHoldCounter(); | |
| 664 | + setState(0); // reset to unlocked state | |
| 665 | + } | |
| 666 | + | |
| 667 | + final int getCount() { return getState(); } | |
| 668 | + } | |
| 669 | + | |
| 670 | + /** | |
| 671 | + * Nonfair version of Sync | |
| 672 | + */ | |
| 673 | + static final class NonfairSync extends Sync { | |
| 674 | + private static final long serialVersionUID = -8159625535654395037L; | |
| 675 | + final boolean writerShouldBlock() { | |
| 676 | + return false; // writers can always barge | |
| 677 | + } | |
| 678 | + final boolean readerShouldBlock() { | |
| 679 | + /* As a heuristic to avoid indefinite writer starvation, | |
| 680 | + * block if the thread that momentarily appears to be head | |
| 681 | + * of queue, if one exists, is a waiting writer. This is | |
| 682 | + * only a probabilistic effect since a new reader will not | |
| 683 | + * block if there is a waiting writer behind other enabled | |
| 684 | + * readers that have not yet drained from the queue. | |
| 685 | + */ | |
| 686 | + return apparentlyFirstQueuedIsExclusive(); | |
| 687 | + } | |
| 688 | + } | |
| 689 | + | |
| 690 | + /** | |
| 691 | + * Fair version of Sync | |
| 692 | + */ | |
| 693 | + static final class FairSync extends Sync { | |
| 694 | + private static final long serialVersionUID = -2274990926593161451L; | |
| 695 | + final boolean writerShouldBlock() { | |
| 696 | + return hasQueuedPredecessors(); | |
| 697 | + } | |
| 698 | + final boolean readerShouldBlock() { | |
| 699 | + return hasQueuedPredecessors(); | |
| 700 | + } | |
| 701 | + } | |
| 702 | + | |
| 703 | + /** | |
| 704 | + * The lock returned by method {@link ReentrantReadWriteLock#readLock}. | |
| 705 | + */ | |
| 706 | + public static class ReadLock implements Lock, java.io.Serializable { | |
| 707 | + private static final long serialVersionUID = -5992448646407690164L; | |
| 708 | + private final Sync sync; | |
| 709 | + | |
| 710 | + /** | |
| 711 | + * Constructor for use by subclasses | |
| 712 | + * | |
| 713 | + * @param lock the outer lock object | |
| 714 | + * @throws NullPointerException if the lock is null | |
| 715 | + */ | |
| 716 | + protected ReadLock(ReentrantReadWriteLock lock) { | |
| 717 | + sync = lock.sync; | |
| 718 | + } | |
| 719 | + | |
| 720 | + /** | |
| 721 | + * Acquires the read lock. | |
| 722 | + * | |
| 723 | + * <p>Acquires the read lock if the write lock is not held by | |
| 724 | + * another thread and returns immediately. | |
| 725 | + * | |
| 726 | + * <p>If the write lock is held by another thread then | |
| 727 | + * the current thread becomes disabled for thread scheduling | |
| 728 | + * purposes and lies dormant until the read lock has been acquired. | |
| 729 | + */ | |
| 730 | + public void lock() { | |
| 731 | + sync.acquireShared(1); | |
| 732 | + } | |
| 733 | + | |
| 734 | + /** | |
| 735 | + * Acquires the read lock unless the current thread is | |
| 736 | + * {@linkplain Thread#interrupt interrupted}. | |
| 737 | + * | |
| 738 | + * <p>Acquires the read lock if the write lock is not held | |
| 739 | + * by another thread and returns immediately. | |
| 740 | + * | |
| 741 | + * <p>If the write lock is held by another thread then the | |
| 742 | + * current thread becomes disabled for thread scheduling | |
| 743 | + * purposes and lies dormant until one of two things happens: | |
| 744 | + * | |
| 745 | + * <ul> | |
| 746 | + * | |
| 747 | + * <li>The read lock is acquired by the current thread; or | |
| 748 | + * | |
| 749 | + * <li>Some other thread {@linkplain Thread#interrupt interrupts} | |
| 750 | + * the current thread. | |
| 751 | + * | |
| 752 | + * </ul> | |
| 753 | + * | |
| 754 | + * <p>If the current thread: | |
| 755 | + * | |
| 756 | + * <ul> | |
| 757 | + * | |
| 758 | + * <li>has its interrupted status set on entry to this method; or | |
| 759 | + * | |
| 760 | + * <li>is {@linkplain Thread#interrupt interrupted} while | |
| 761 | + * acquiring the read lock, | |
| 762 | + * | |
| 763 | + * </ul> | |
| 764 | + * | |
| 765 | + * then {@link InterruptedException} is thrown and the current | |
| 766 | + * thread's interrupted status is cleared. | |
| 767 | + * | |
| 768 | + * <p>In this implementation, as this method is an explicit | |
| 769 | + * interruption point, preference is given to responding to | |
| 770 | + * the interrupt over normal or reentrant acquisition of the | |
| 771 | + * lock. | |
| 772 | + * | |
| 773 | + * @throws InterruptedException if the current thread is interrupted | |
| 774 | + */ | |
| 775 | + public void lockInterruptibly() throws InterruptedException { | |
| 776 | + sync.acquireSharedInterruptibly(1); | |
| 777 | + } | |
| 778 | + | |
| 779 | + /** | |
| 780 | + * Acquires the read lock only if the write lock is not held by | |
| 781 | + * another thread at the time of invocation. | |
| 782 | + * | |
| 783 | + * <p>Acquires the read lock if the write lock is not held by | |
| 784 | + * another thread and returns immediately with the value | |
| 785 | + * {@code true}. Even when this lock has been set to use a | |
| 786 | + * fair ordering policy, a call to {@code tryLock()} | |
| 787 | + * <em>will</em> immediately acquire the read lock if it is | |
| 788 | + * available, whether or not other threads are currently | |
| 789 | + * waiting for the read lock. This "barging" behavior | |
| 790 | + * can be useful in certain circumstances, even though it | |
| 791 | + * breaks fairness. If you want to honor the fairness setting | |
| 792 | + * for this lock, then use {@link #tryLock(long, TimeUnit) | |
| 793 | + * tryLock(0, TimeUnit.SECONDS) } which is almost equivalent | |
| 794 | + * (it also detects interruption). | |
| 795 | + * | |
| 796 | + * <p>If the write lock is held by another thread then | |
| 797 | + * this method will return immediately with the value | |
| 798 | + * {@code false}. | |
| 799 | + * | |
| 800 | + * @return {@code true} if the read lock was acquired | |
| 801 | + */ | |
| 802 | + public boolean tryLock() { | |
| 803 | + return sync.tryReadLock(); | |
| 804 | + } | |
| 805 | + | |
| 806 | + /** | |
| 807 | + * Acquires the read lock if the write lock is not held by | |
| 808 | + * another thread within the given waiting time and the | |
| 809 | + * current thread has not been {@linkplain Thread#interrupt | |
| 810 | + * interrupted}. | |
| 811 | + * | |
| 812 | + * <p>Acquires the read lock if the write lock is not held by | |
| 813 | + * another thread and returns immediately with the value | |
| 814 | + * {@code true}. If this lock has been set to use a fair | |
| 815 | + * ordering policy then an available lock <em>will not</em> be | |
| 816 | + * acquired if any other threads are waiting for the | |
| 817 | + * lock. This is in contrast to the {@link #tryLock()} | |
| 818 | + * method. If you want a timed {@code tryLock} that does | |
| 819 | + * permit barging on a fair lock then combine the timed and | |
| 820 | + * un-timed forms together: | |
| 821 | + * | |
| 822 | + * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... } | |
| 823 | + * </pre> | |
| 824 | + * | |
| 825 | + * <p>If the write lock is held by another thread then the | |
| 826 | + * current thread becomes disabled for thread scheduling | |
| 827 | + * purposes and lies dormant until one of three things happens: | |
| 828 | + * | |
| 829 | + * <ul> | |
| 830 | + * | |
| 831 | + * <li>The read lock is acquired by the current thread; or | |
| 832 | + * | |
| 833 | + * <li>Some other thread {@linkplain Thread#interrupt interrupts} | |
| 834 | + * the current thread; or | |
| 835 | + * | |
| 836 | + * <li>The specified waiting time elapses. | |
| 837 | + * | |
| 838 | + * </ul> | |
| 839 | + * | |
| 840 | + * <p>If the read lock is acquired then the value {@code true} is | |
| 841 | + * returned. | |
| 842 | + * | |
| 843 | + * <p>If the current thread: | |
| 844 | + * | |
| 845 | + * <ul> | |
| 846 | + * | |
| 847 | + * <li>has its interrupted status set on entry to this method; or | |
| 848 | + * | |
| 849 | + * <li>is {@linkplain Thread#interrupt interrupted} while | |
| 850 | + * acquiring the read lock, | |
| 851 | + * | |
| 852 | + * </ul> then {@link InterruptedException} is thrown and the | |
| 853 | + * current thread's interrupted status is cleared. | |
| 854 | + * | |
| 855 | + * <p>If the specified waiting time elapses then the value | |
| 856 | + * {@code false} is returned. If the time is less than or | |
| 857 | + * equal to zero, the method will not wait at all. | |
| 858 | + * | |
| 859 | + * <p>In this implementation, as this method is an explicit | |
| 860 | + * interruption point, preference is given to responding to | |
| 861 | + * the interrupt over normal or reentrant acquisition of the | |
| 862 | + * lock, and over reporting the elapse of the waiting time. | |
| 863 | + * | |
| 864 | + * @param timeout the time to wait for the read lock | |
| 865 | + * @param unit the time unit of the timeout argument | |
| 866 | + * @return {@code true} if the read lock was acquired | |
| 867 | + * @throws InterruptedException if the current thread is interrupted | |
| 868 | + * @throws NullPointerException if the time unit is null | |
| 869 | + * | |
| 870 | + */ | |
| 871 | + public boolean tryLock(long timeout, TimeUnit unit) | |
| 872 | + throws InterruptedException { | |
| 873 | + return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); | |
| 874 | + } | |
| 875 | + | |
| 876 | + /** | |
| 877 | + * Attempts to release this lock. | |
| 878 | + * | |
| 879 | + * <p> If the number of readers is now zero then the lock | |
| 880 | + * is made available for write lock attempts. | |
| 881 | + */ | |
| 882 | + public void unlock() { | |
| 883 | + sync.releaseShared(1); | |
| 884 | + } | |
| 885 | + | |
| 886 | + /** | |
| 887 | + * Throws {@code UnsupportedOperationException} because | |
| 888 | + * {@code ReadLocks} do not support conditions. | |
| 889 | + * | |
| 890 | + * @throws UnsupportedOperationException always | |
| 891 | + */ | |
| 892 | + public Condition newCondition() { | |
| 893 | + throw new UnsupportedOperationException(); | |
| 894 | + } | |
| 895 | + | |
| 896 | + /** | |
| 897 | + * Returns a string identifying this lock, as well as its lock state. | |
| 898 | + * The state, in brackets, includes the String {@code "Read locks ="} | |
| 899 | + * followed by the number of held read locks. | |
| 900 | + * | |
| 901 | + * @return a string identifying this lock, as well as its lock state | |
| 902 | + */ | |
| 903 | + public String toString() { | |
| 904 | + int r = sync.getReadLockCount(); | |
| 905 | + return super.toString() + | |
| 906 | + "[Read locks = " + r + "]"; | |
| 907 | + } | |
| 908 | + } | |
| 909 | + | |
| 910 | + /** | |
| 911 | + * The lock returned by method {@link ReentrantReadWriteLock#writeLock}. | |
| 912 | + */ | |
| 913 | + public static class WriteLock implements Lock, java.io.Serializable { | |
| 914 | + private static final long serialVersionUID = -4992448646407690164L; | |
| 915 | + private final Sync sync; | |
| 916 | + | |
| 917 | + /** | |
| 918 | + * Constructor for use by subclasses | |
| 919 | + * | |
| 920 | + * @param lock the outer lock object | |
| 921 | + * @throws NullPointerException if the lock is null | |
| 922 | + */ | |
| 923 | + protected WriteLock(ReentrantReadWriteLock lock) { | |
| 924 | + sync = lock.sync; | |
| 925 | + } | |
| 926 | + | |
| 927 | + /** | |
| 928 | + * Acquires the write lock. | |
| 929 | + * | |
| 930 | + * <p>Acquires the write lock if neither the read nor write lock | |
| 931 | + * are held by another thread | |
| 932 | + * and returns immediately, setting the write lock hold count to | |
| 933 | + * one. | |
| 934 | + * | |
| 935 | + * <p>If the current thread already holds the write lock then the | |
| 936 | + * hold count is incremented by one and the method returns | |
| 937 | + * immediately. | |
| 938 | + * | |
| 939 | + * <p>If the lock is held by another thread then the current | |
| 940 | + * thread becomes disabled for thread scheduling purposes and | |
| 941 | + * lies dormant until the write lock has been acquired, at which | |
| 942 | + * time the write lock hold count is set to one. | |
| 943 | + */ | |
| 944 | + public void lock() { | |
| 945 | + sync.acquire(1); | |
| 946 | + } | |
| 947 | + | |
| 948 | + /** | |
| 949 | + * Acquires the write lock unless the current thread is | |
| 950 | + * {@linkplain Thread#interrupt interrupted}. | |
| 951 | + * | |
| 952 | + * <p>Acquires the write lock if neither the read nor write lock | |
| 953 | + * are held by another thread | |
| 954 | + * and returns immediately, setting the write lock hold count to | |
| 955 | + * one. | |
| 956 | + * | |
| 957 | + * <p>If the current thread already holds this lock then the | |
| 958 | + * hold count is incremented by one and the method returns | |
| 959 | + * immediately. | |
| 960 | + * | |
| 961 | + * <p>If the lock is held by another thread then the current | |
| 962 | + * thread becomes disabled for thread scheduling purposes and | |
| 963 | + * lies dormant until one of two things happens: | |
| 964 | + * | |
| 965 | + * <ul> | |
| 966 | + * | |
| 967 | + * <li>The write lock is acquired by the current thread; or | |
| 968 | + * | |
| 969 | + * <li>Some other thread {@linkplain Thread#interrupt interrupts} | |
| 970 | + * the current thread. | |
| 971 | + * | |
| 972 | + * </ul> | |
| 973 | + * | |
| 974 | + * <p>If the write lock is acquired by the current thread then the | |
| 975 | + * lock hold count is set to one. | |
| 976 | + * | |
| 977 | + * <p>If the current thread: | |
| 978 | + * | |
| 979 | + * <ul> | |
| 980 | + * | |
| 981 | + * <li>has its interrupted status set on entry to this method; | |
| 982 | + * or | |
| 983 | + * | |
| 984 | + * <li>is {@linkplain Thread#interrupt interrupted} while | |
| 985 | + * acquiring the write lock, | |
| 986 | + * | |
| 987 | + * </ul> | |
| 988 | + * | |
| 989 | + * then {@link InterruptedException} is thrown and the current | |
| 990 | + * thread's interrupted status is cleared. | |
| 991 | + * | |
| 992 | + * <p>In this implementation, as this method is an explicit | |
| 993 | + * interruption point, preference is given to responding to | |
| 994 | + * the interrupt over normal or reentrant acquisition of the | |
| 995 | + * lock. | |
| 996 | + * | |
| 997 | + * @throws InterruptedException if the current thread is interrupted | |
| 998 | + */ | |
| 999 | + public void lockInterruptibly() throws InterruptedException { | |
| 1000 | + sync.acquireInterruptibly(1); | |
| 1001 | + } | |
| 1002 | + | |
| 1003 | + /** | |
| 1004 | + * Acquires the write lock only if it is not held by another thread | |
| 1005 | + * at the time of invocation. | |
| 1006 | + * | |
| 1007 | + * <p>Acquires the write lock if neither the read nor write lock | |
| 1008 | + * are held by another thread | |
| 1009 | + * and returns immediately with the value {@code true}, | |
| 1010 | + * setting the write lock hold count to one. Even when this lock has | |
| 1011 | + * been set to use a fair ordering policy, a call to | |
| 1012 | + * {@code tryLock()} <em>will</em> immediately acquire the | |
| 1013 | + * lock if it is available, whether or not other threads are | |
| 1014 | + * currently waiting for the write lock. This "barging" | |
| 1015 | + * behavior can be useful in certain circumstances, even | |
| 1016 | + * though it breaks fairness. If you want to honor the | |
| 1017 | + * fairness setting for this lock, then use {@link | |
| 1018 | + * #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) } | |
| 1019 | + * which is almost equivalent (it also detects interruption). | |
| 1020 | + * | |
| 1021 | + * <p> If the current thread already holds this lock then the | |
| 1022 | + * hold count is incremented by one and the method returns | |
| 1023 | + * {@code true}. | |
| 1024 | + * | |
| 1025 | + * <p>If the lock is held by another thread then this method | |
| 1026 | + * will return immediately with the value {@code false}. | |
| 1027 | + * | |
| 1028 | + * @return {@code true} if the lock was free and was acquired | |
| 1029 | + * by the current thread, or the write lock was already held | |
| 1030 | + * by the current thread; and {@code false} otherwise. | |
| 1031 | + */ | |
| 1032 | + public boolean tryLock( ) { | |
| 1033 | + return sync.tryWriteLock(); | |
| 1034 | + } | |
| 1035 | + | |
| 1036 | + /** | |
| 1037 | + * Acquires the write lock if it is not held by another thread | |
| 1038 | + * within the given waiting time and the current thread has | |
| 1039 | + * not been {@linkplain Thread#interrupt interrupted}. | |
| 1040 | + * | |
| 1041 | + * <p>Acquires the write lock if neither the read nor write lock | |
| 1042 | + * are held by another thread | |
| 1043 | + * and returns immediately with the value {@code true}, | |
| 1044 | + * setting the write lock hold count to one. If this lock has been | |
| 1045 | + * set to use a fair ordering policy then an available lock | |
| 1046 | + * <em>will not</em> be acquired if any other threads are | |
| 1047 | + * waiting for the write lock. This is in contrast to the {@link | |
| 1048 | + * #tryLock()} method. If you want a timed {@code tryLock} | |
| 1049 | + * that does permit barging on a fair lock then combine the | |
| 1050 | + * timed and un-timed forms together: | |
| 1051 | + * | |
| 1052 | + * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... } | |
| 1053 | + * </pre> | |
| 1054 | + * | |
| 1055 | + * <p>If the current thread already holds this lock then the | |
| 1056 | + * hold count is incremented by one and the method returns | |
| 1057 | + * {@code true}. | |
| 1058 | + * | |
| 1059 | + * <p>If the lock is held by another thread then the current | |
| 1060 | + * thread becomes disabled for thread scheduling purposes and | |
| 1061 | + * lies dormant until one of three things happens: | |
| 1062 | + * | |
| 1063 | + * <ul> | |
| 1064 | + * | |
| 1065 | + * <li>The write lock is acquired by the current thread; or | |
| 1066 | + * | |
| 1067 | + * <li>Some other thread {@linkplain Thread#interrupt interrupts} | |
| 1068 | + * the current thread; or | |
| 1069 | + * | |
| 1070 | + * <li>The specified waiting time elapses | |
| 1071 | + * | |
| 1072 | + * </ul> | |
| 1073 | + * | |
| 1074 | + * <p>If the write lock is acquired then the value {@code true} is | |
| 1075 | + * returned and the write lock hold count is set to one. | |
| 1076 | + * | |
| 1077 | + * <p>If the current thread: | |
| 1078 | + * | |
| 1079 | + * <ul> | |
| 1080 | + * | |
| 1081 | + * <li>has its interrupted status set on entry to this method; | |
| 1082 | + * or | |
| 1083 | + * | |
| 1084 | + * <li>is {@linkplain Thread#interrupt interrupted} while | |
| 1085 | + * acquiring the write lock, | |
| 1086 | + * | |
| 1087 | + * </ul> | |
| 1088 | + * | |
| 1089 | + * then {@link InterruptedException} is thrown and the current | |
| 1090 | + * thread's interrupted status is cleared. | |
| 1091 | + * | |
| 1092 | + * <p>If the specified waiting time elapses then the value | |
| 1093 | + * {@code false} is returned. If the time is less than or | |
| 1094 | + * equal to zero, the method will not wait at all. | |
| 1095 | + * | |
| 1096 | + * <p>In this implementation, as this method is an explicit | |
| 1097 | + * interruption point, preference is given to responding to | |
| 1098 | + * the interrupt over normal or reentrant acquisition of the | |
| 1099 | + * lock, and over reporting the elapse of the waiting time. | |
| 1100 | + * | |
| 1101 | + * @param timeout the time to wait for the write lock | |
| 1102 | + * @param unit the time unit of the timeout argument | |
| 1103 | + * | |
| 1104 | + * @return {@code true} if the lock was free and was acquired | |
| 1105 | + * by the current thread, or the write lock was already held by the | |
| 1106 | + * current thread; and {@code false} if the waiting time | |
| 1107 | + * elapsed before the lock could be acquired. | |
| 1108 | + * | |
| 1109 | + * @throws InterruptedException if the current thread is interrupted | |
| 1110 | + * @throws NullPointerException if the time unit is null | |
| 1111 | + * | |
| 1112 | + */ | |
| 1113 | + public boolean tryLock(long timeout, TimeUnit unit) | |
| 1114 | + throws InterruptedException { | |
| 1115 | + return sync.tryAcquireNanos(1, unit.toNanos(timeout)); | |
| 1116 | + } | |
| 1117 | + | |
| 1118 | + /** | |
| 1119 | + * Attempts to release this lock. | |
| 1120 | + * | |
| 1121 | + * <p>If the current thread is the holder of this lock then | |
| 1122 | + * the hold count is decremented. If the hold count is now | |
| 1123 | + * zero then the lock is released. If the current thread is | |
| 1124 | + * not the holder of this lock then {@link | |
| 1125 | + * IllegalMonitorStateException} is thrown. | |
| 1126 | + * | |
| 1127 | + * @throws IllegalMonitorStateException if the current thread does not | |
| 1128 | + * hold this lock. | |
| 1129 | + */ | |
| 1130 | + public void unlock() { | |
| 1131 | + sync.release(1); | |
| 1132 | + } | |
| 1133 | + | |
| 1134 | + /** | |
| 1135 | + * Returns a {@link Condition} instance for use with this | |
| 1136 | + * {@link Lock} instance. | |
| 1137 | + * <p>The returned {@link Condition} instance supports the same | |
| 1138 | + * usages as do the {@link Object} monitor methods ({@link | |
| 1139 | + * Object#wait() wait}, {@link Object#notify notify}, and {@link | |
| 1140 | + * Object#notifyAll notifyAll}) when used with the built-in | |
| 1141 | + * monitor lock. | |
| 1142 | + * | |
| 1143 | + * <ul> | |
| 1144 | + * | |
| 1145 | + * <li>If this write lock is not held when any {@link | |
| 1146 | + * Condition} method is called then an {@link | |
| 1147 | + * IllegalMonitorStateException} is thrown. (Read locks are | |
| 1148 | + * held independently of write locks, so are not checked or | |
| 1149 | + * affected. However it is essentially always an error to | |
| 1150 | + * invoke a condition waiting method when the current thread | |
| 1151 | + * has also acquired read locks, since other threads that | |
| 1152 | + * could unblock it will not be able to acquire the write | |
| 1153 | + * lock.) | |
| 1154 | + * | |
| 1155 | + * <li>When the condition {@linkplain Condition#await() waiting} | |
| 1156 | + * methods are called the write lock is released and, before | |
| 1157 | + * they return, the write lock is reacquired and the lock hold | |
| 1158 | + * count restored to what it was when the method was called. | |
| 1159 | + * | |
| 1160 | + * <li>If a thread is {@linkplain Thread#interrupt interrupted} while | |
| 1161 | + * waiting then the wait will terminate, an {@link | |
| 1162 | + * InterruptedException} will be thrown, and the thread's | |
| 1163 | + * interrupted status will be cleared. | |
| 1164 | + * | |
| 1165 | + * <li> Waiting threads are signalled in FIFO order. | |
| 1166 | + * | |
| 1167 | + * <li>The ordering of lock reacquisition for threads returning | |
| 1168 | + * from waiting methods is the same as for threads initially | |
| 1169 | + * acquiring the lock, which is in the default case not specified, | |
| 1170 | + * but for <em>fair</em> locks favors those threads that have been | |
| 1171 | + * waiting the longest. | |
| 1172 | + * | |
| 1173 | + * </ul> | |
| 1174 | + * | |
| 1175 | + * @return the Condition object | |
| 1176 | + */ | |
| 1177 | + public Condition newCondition() { | |
| 1178 | + return sync.newCondition(); | |
| 1179 | + } | |
| 1180 | + | |
| 1181 | + /** | |
| 1182 | + * Returns a string identifying this lock, as well as its lock | |
| 1183 | + * state. The state, in brackets includes either the String | |
| 1184 | + * {@code "Unlocked"} or the String {@code "Locked by"} | |
| 1185 | + * followed by the {@linkplain Thread#getName name} of the owning thread. | |
| 1186 | + * | |
| 1187 | + * @return a string identifying this lock, as well as its lock state | |
| 1188 | + */ | |
| 1189 | + public String toString() { | |
| 1190 | + Thread o = sync.getOwner(); | |
| 1191 | + return super.toString() + ((o == null) ? | |
| 1192 | + "[Unlocked]" : | |
| 1193 | + "[Locked by thread " + o.getName() + "]"); | |
| 1194 | + } | |
| 1195 | + | |
| 1196 | + /** | |
| 1197 | + * Queries if this write lock is held by the current thread. | |
| 1198 | + * Identical in effect to {@link | |
| 1199 | + * ReentrantReadWriteLock#isWriteLockedByCurrentThread}. | |
| 1200 | + * | |
| 1201 | + * @return {@code true} if the current thread holds this lock and | |
| 1202 | + * {@code false} otherwise | |
| 1203 | + * @since 1.6 | |
| 1204 | + */ | |
| 1205 | + public boolean isHeldByCurrentThread() { | |
| 1206 | + return sync.isHeldExclusively(); | |
| 1207 | + } | |
| 1208 | + | |
| 1209 | + /** | |
| 1210 | + * Queries the number of holds on this write lock by the current | |
| 1211 | + * thread. A thread has a hold on a lock for each lock action | |
| 1212 | + * that is not matched by an unlock action. Identical in effect | |
| 1213 | + * to {@link ReentrantReadWriteLock#getWriteHoldCount}. | |
| 1214 | + * | |
| 1215 | + * @return the number of holds on this lock by the current thread, | |
| 1216 | + * or zero if this lock is not held by the current thread | |
| 1217 | + * @since 1.6 | |
| 1218 | + */ | |
| 1219 | + public int getHoldCount() { | |
| 1220 | + return sync.getWriteHoldCount(); | |
| 1221 | + } | |
| 1222 | + } | |
| 1223 | + | |
| 1224 | + // Instrumentation and status | |
| 1225 | + | |
| 1226 | + /** | |
| 1227 | + * Returns {@code true} if this lock has fairness set true. | |
| 1228 | + * | |
| 1229 | + * @return {@code true} if this lock has fairness set true | |
| 1230 | + */ | |
| 1231 | + public final boolean isFair() { | |
| 1232 | + return sync instanceof FairSync; | |
| 1233 | + } | |
| 1234 | + | |
| 1235 | + /** | |
| 1236 | + * Returns the thread that currently owns the write lock, or | |
| 1237 | + * {@code null} if not owned. When this method is called by a | |
| 1238 | + * thread that is not the owner, the return value reflects a | |
| 1239 | + * best-effort approximation of current lock status. For example, | |
| 1240 | + * the owner may be momentarily {@code null} even if there are | |
| 1241 | + * threads trying to acquire the lock but have not yet done so. | |
| 1242 | + * This method is designed to facilitate construction of | |
| 1243 | + * subclasses that provide more extensive lock monitoring | |
| 1244 | + * facilities. | |
| 1245 | + * | |
| 1246 | + * @return the owner, or {@code null} if not owned | |
| 1247 | + */ | |
| 1248 | + protected Thread getOwner() { | |
| 1249 | + return sync.getOwner(); | |
| 1250 | + } | |
| 1251 | + | |
| 1252 | + /** | |
| 1253 | + * Queries the number of read locks held for this lock. This | |
| 1254 | + * method is designed for use in monitoring system state, not for | |
| 1255 | + * synchronization control. | |
| 1256 | + * @return the number of read locks held. | |
| 1257 | + */ | |
| 1258 | + public int getReadLockCount() { | |
| 1259 | + return sync.getReadLockCount(); | |
| 1260 | + } | |
| 1261 | + | |
| 1262 | + /** | |
| 1263 | + * Queries if the write lock is held by any thread. This method is | |
| 1264 | + * designed for use in monitoring system state, not for | |
| 1265 | + * synchronization control. | |
| 1266 | + * | |
| 1267 | + * @return {@code true} if any thread holds the write lock and | |
| 1268 | + * {@code false} otherwise | |
| 1269 | + */ | |
| 1270 | + public boolean isWriteLocked() { | |
| 1271 | + return sync.isWriteLocked(); | |
| 1272 | + } | |
| 1273 | + | |
| 1274 | + /** | |
| 1275 | + * Queries if the write lock is held by the current thread. | |
| 1276 | + * | |
| 1277 | + * @return {@code true} if the current thread holds the write lock and | |
| 1278 | + * {@code false} otherwise | |
| 1279 | + */ | |
| 1280 | + public boolean isWriteLockedByCurrentThread() { | |
| 1281 | + return sync.isHeldExclusively(); | |
| 1282 | + } | |
| 1283 | + | |
| 1284 | + /** | |
| 1285 | + * Queries the number of reentrant write holds on this lock by the | |
| 1286 | + * current thread. A writer thread has a hold on a lock for | |
| 1287 | + * each lock action that is not matched by an unlock action. | |
| 1288 | + * | |
| 1289 | + * @return the number of holds on the write lock by the current thread, | |
| 1290 | + * or zero if the write lock is not held by the current thread | |
| 1291 | + */ | |
| 1292 | + public int getWriteHoldCount() { | |
| 1293 | + return sync.getWriteHoldCount(); | |
| 1294 | + } | |
| 1295 | + | |
| 1296 | + /** | |
| 1297 | + * Queries the number of reentrant read holds on this lock by the | |
| 1298 | + * current thread. A reader thread has a hold on a lock for | |
| 1299 | + * each lock action that is not matched by an unlock action. | |
| 1300 | + * | |
| 1301 | + * @return the number of holds on the read lock by the current thread, | |
| 1302 | + * or zero if the read lock is not held by the current thread | |
| 1303 | + * @since 1.6 | |
| 1304 | + */ | |
| 1305 | + public int getReadHoldCount() { | |
| 1306 | + return sync.getReadHoldCount(); | |
| 1307 | + } | |
| 1308 | + | |
| 1309 | + /** | |
| 1310 | + * Returns a collection containing threads that may be waiting to | |
| 1311 | + * acquire the write lock. Because the actual set of threads may | |
| 1312 | + * change dynamically while constructing this result, the returned | |
| 1313 | + * collection is only a best-effort estimate. The elements of the | |
| 1314 | + * returned collection are in no particular order. This method is | |
| 1315 | + * designed to facilitate construction of subclasses that provide | |
| 1316 | + * more extensive lock monitoring facilities. | |
| 1317 | + * | |
| 1318 | + * @return the collection of threads | |
| 1319 | + */ | |
| 1320 | + protected Collection<Thread> getQueuedWriterThreads() { | |
| 1321 | + return sync.getExclusiveQueuedThreads(); | |
| 1322 | + } | |
| 1323 | + | |
| 1324 | + /** | |
| 1325 | + * Returns a collection containing threads that may be waiting to | |
| 1326 | + * acquire the read lock. Because the actual set of threads may | |
| 1327 | + * change dynamically while constructing this result, the returned | |
| 1328 | + * collection is only a best-effort estimate. The elements of the | |
| 1329 | + * returned collection are in no particular order. This method is | |
| 1330 | + * designed to facilitate construction of subclasses that provide | |
| 1331 | + * more extensive lock monitoring facilities. | |
| 1332 | + * | |
| 1333 | + * @return the collection of threads | |
| 1334 | + */ | |
| 1335 | + protected Collection<Thread> getQueuedReaderThreads() { | |
| 1336 | + return sync.getSharedQueuedThreads(); | |
| 1337 | + } | |
| 1338 | + | |
| 1339 | + /** | |
| 1340 | + * Queries whether any threads are waiting to acquire the read or | |
| 1341 | + * write lock. Note that because cancellations may occur at any | |
| 1342 | + * time, a {@code true} return does not guarantee that any other | |
| 1343 | + * thread will ever acquire a lock. This method is designed | |
| 1344 | + * primarily for use in monitoring of the system state. | |
| 1345 | + * | |
| 1346 | + * @return {@code true} if there may be other threads waiting to | |
| 1347 | + * acquire the lock | |
| 1348 | + */ | |
| 1349 | + public final boolean hasQueuedThreads() { | |
| 1350 | + return sync.hasQueuedThreads(); | |
| 1351 | + } | |
| 1352 | + | |
| 1353 | + /** | |
| 1354 | + * Queries whether the given thread is waiting to acquire either | |
| 1355 | + * the read or write lock. Note that because cancellations may | |
| 1356 | + * occur at any time, a {@code true} return does not guarantee | |
| 1357 | + * that this thread will ever acquire a lock. This method is | |
| 1358 | + * designed primarily for use in monitoring of the system state. | |
| 1359 | + * | |
| 1360 | + * @param thread the thread | |
| 1361 | + * @return {@code true} if the given thread is queued waiting for this lock | |
| 1362 | + * @throws NullPointerException if the thread is null | |
| 1363 | + */ | |
| 1364 | + public final boolean hasQueuedThread(Thread thread) { | |
| 1365 | + return sync.isQueued(thread); | |
| 1366 | + } | |
| 1367 | + | |
| 1368 | + /** | |
| 1369 | + * Returns an estimate of the number of threads waiting to acquire | |
| 1370 | + * either the read or write lock. The value is only an estimate | |
| 1371 | + * because the number of threads may change dynamically while this | |
| 1372 | + * method traverses internal data structures. This method is | |
| 1373 | + * designed for use in monitoring of the system state, not for | |
| 1374 | + * synchronization control. | |
| 1375 | + * | |
| 1376 | + * @return the estimated number of threads waiting for this lock | |
| 1377 | + */ | |
| 1378 | + public final int getQueueLength() { | |
| 1379 | + return sync.getQueueLength(); | |
| 1380 | + } | |
| 1381 | + | |
| 1382 | + /** | |
| 1383 | + * Returns a collection containing threads that may be waiting to | |
| 1384 | + * acquire either the read or write lock. Because the actual set | |
| 1385 | + * of threads may change dynamically while constructing this | |
| 1386 | + * result, the returned collection is only a best-effort estimate. | |
| 1387 | + * The elements of the returned collection are in no particular | |
| 1388 | + * order. This method is designed to facilitate construction of | |
| 1389 | + * subclasses that provide more extensive monitoring facilities. | |
| 1390 | + * | |
| 1391 | + * @return the collection of threads | |
| 1392 | + */ | |
| 1393 | + protected Collection<Thread> getQueuedThreads() { | |
| 1394 | + return sync.getQueuedThreads(); | |
| 1395 | + } | |
| 1396 | + | |
| 1397 | + /** | |
| 1398 | + * Queries whether any threads are waiting on the given condition | |
| 1399 | + * associated with the write lock. Note that because timeouts and | |
| 1400 | + * interrupts may occur at any time, a {@code true} return does | |
| 1401 | + * not guarantee that a future {@code signal} will awaken any | |
| 1402 | + * threads. This method is designed primarily for use in | |
| 1403 | + * monitoring of the system state. | |
| 1404 | + * | |
| 1405 | + * @param condition the condition | |
| 1406 | + * @return {@code true} if there are any waiting threads | |
| 1407 | + * @throws IllegalMonitorStateException if this lock is not held | |
| 1408 | + * @throws IllegalArgumentException if the given condition is | |
| 1409 | + * not associated with this lock | |
| 1410 | + * @throws NullPointerException if the condition is null | |
| 1411 | + */ | |
| 1412 | + public boolean hasWaiters(Condition condition) { | |
| 1413 | + if (condition == null) | |
| 1414 | + throw new NullPointerException(); | |
| 1415 | + if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) | |
| 1416 | + throw new IllegalArgumentException("not owner"); | |
| 1417 | + return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition); | |
| 1418 | + } | |
| 1419 | + | |
| 1420 | + /** | |
| 1421 | + * Returns an estimate of the number of threads waiting on the | |
| 1422 | + * given condition associated with the write lock. Note that because | |
| 1423 | + * timeouts and interrupts may occur at any time, the estimate | |
| 1424 | + * serves only as an upper bound on the actual number of waiters. | |
| 1425 | + * This method is designed for use in monitoring of the system | |
| 1426 | + * state, not for synchronization control. | |
| 1427 | + * | |
| 1428 | + * @param condition the condition | |
| 1429 | + * @return the estimated number of waiting threads | |
| 1430 | + * @throws IllegalMonitorStateException if this lock is not held | |
| 1431 | + * @throws IllegalArgumentException if the given condition is | |
| 1432 | + * not associated with this lock | |
| 1433 | + * @throws NullPointerException if the condition is null | |
| 1434 | + */ | |
| 1435 | + public int getWaitQueueLength(Condition condition) { | |
| 1436 | + if (condition == null) | |
| 1437 | + throw new NullPointerException(); | |
| 1438 | + if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) | |
| 1439 | + throw new IllegalArgumentException("not owner"); | |
| 1440 | + return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition); | |
| 1441 | + } | |
| 1442 | + | |
| 1443 | + /** | |
| 1444 | + * Returns a collection containing those threads that may be | |
| 1445 | + * waiting on the given condition associated with the write lock. | |
| 1446 | + * Because the actual set of threads may change dynamically while | |
| 1447 | + * constructing this result, the returned collection is only a | |
| 1448 | + * best-effort estimate. The elements of the returned collection | |
| 1449 | + * are in no particular order. This method is designed to | |
| 1450 | + * facilitate construction of subclasses that provide more | |
| 1451 | + * extensive condition monitoring facilities. | |
| 1452 | + * | |
| 1453 | + * @param condition the condition | |
| 1454 | + * @return the collection of threads | |
| 1455 | + * @throws IllegalMonitorStateException if this lock is not held | |
| 1456 | + * @throws IllegalArgumentException if the given condition is | |
| 1457 | + * not associated with this lock | |
| 1458 | + * @throws NullPointerException if the condition is null | |
| 1459 | + */ | |
| 1460 | + protected Collection<Thread> getWaitingThreads(Condition condition) { | |
| 1461 | + if (condition == null) | |
| 1462 | + throw new NullPointerException(); | |
| 1463 | + if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) | |
| 1464 | + throw new IllegalArgumentException("not owner"); | |
| 1465 | + return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition); | |
| 1466 | + } | |
| 1467 | + | |
| 1468 | + /** | |
| 1469 | + * Returns a string identifying this lock, as well as its lock state. | |
| 1470 | + * The state, in brackets, includes the String {@code "Write locks ="} | |
| 1471 | + * followed by the number of reentrantly held write locks, and the | |
| 1472 | + * String {@code "Read locks ="} followed by the number of held | |
| 1473 | + * read locks. | |
| 1474 | + * | |
| 1475 | + * @return a string identifying this lock, as well as its lock state | |
| 1476 | + */ | |
| 1477 | + public String toString() { | |
| 1478 | + int c = sync.getCount(); | |
| 1479 | + int w = Sync.exclusiveCount(c); | |
| 1480 | + int r = Sync.sharedCount(c); | |
| 1481 | + | |
| 1482 | + return super.toString() + | |
| 1483 | + "[Write locks = " + w + ", Read locks = " + r + "]"; | |
| 1484 | + } | |
| 1485 | + | |
| 1486 | +} | |
| @@ -0,0 +1,17 @@ | ||
| 1 | +<../../../../../../mkconfig | |
| 2 | + | |
| 3 | +TARG=\ | |
| 4 | + AbstractOwnableSynchronizer.dis\ | |
| 5 | + AbstractQueuedLongSynchronizer.dis\ | |
| 6 | + AbstractQueuedSynchronizer.dis\ | |
| 7 | + Condition.dis\ | |
| 8 | + Lock.dis\ | |
| 9 | + LockSupport.dis\ | |
| 10 | + package-info.dis\ | |
| 11 | + ReadWriteLock.dis\ | |
| 12 | + ReentrantLock.dis\ | |
| 13 | + ReentrantReadWriteLock.dis\ | |
| 14 | + | |
| 15 | +DISBIN=$ROOT/java/dis/java/java/java/util/concurrent/locks | |
| 16 | + | |
| 17 | +<$ROOT/mkfiles/mkjava | |
| @@ -0,0 +1,79 @@ | ||
| 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 | +/** | |
| 37 | + * Interfaces and classes providing a framework for locking and waiting | |
| 38 | + * for conditions that is distinct from built-in synchronization and | |
| 39 | + * monitors. The framework permits much greater flexibility in the use of | |
| 40 | + * locks and conditions, at the expense of more awkward syntax. | |
| 41 | + * | |
| 42 | + * <p>The {@link java.util.concurrent.locks.Lock} interface supports | |
| 43 | + * locking disciplines that differ in semantics (reentrant, fair, etc), | |
| 44 | + * and that can be used in non-block-structured contexts including | |
| 45 | + * hand-over-hand and lock reordering algorithms. The main implementation | |
| 46 | + * is {@link java.util.concurrent.locks.ReentrantLock}. | |
| 47 | + * | |
| 48 | + * <p>The {@link java.util.concurrent.locks.ReadWriteLock} interface | |
| 49 | + * similarly defines locks that may be shared among readers but are | |
| 50 | + * exclusive to writers. Only a single implementation, {@link | |
| 51 | + * java.util.concurrent.locks.ReentrantReadWriteLock}, is provided, since | |
| 52 | + * it covers most standard usage contexts. But programmers may create | |
| 53 | + * their own implementations to cover nonstandard requirements. | |
| 54 | + * | |
| 55 | + * <p>The {@link java.util.concurrent.locks.Condition} interface | |
| 56 | + * describes condition variables that may be associated with Locks. | |
| 57 | + * These are similar in usage to the implicit monitors accessed using | |
| 58 | + * {@code Object.wait}, but offer extended capabilities. | |
| 59 | + * In particular, multiple {@code Condition} objects may be associated | |
| 60 | + * with a single {@code Lock}. To avoid compatibility issues, the | |
| 61 | + * names of {@code Condition} methods are different from the | |
| 62 | + * corresponding {@code Object} versions. | |
| 63 | + * | |
| 64 | + * <p>The {@link java.util.concurrent.locks.AbstractQueuedSynchronizer} | |
| 65 | + * class serves as a useful superclass for defining locks and other | |
| 66 | + * synchronizers that rely on queuing blocked threads. The {@link | |
| 67 | + * java.util.concurrent.locks.AbstractQueuedLongSynchronizer} class | |
| 68 | + * provides the same functionality but extends support to 64 bits of | |
| 69 | + * synchronization state. Both extend class {@link | |
| 70 | + * java.util.concurrent.locks.AbstractOwnableSynchronizer}, a simple | |
| 71 | + * class that helps record the thread currently holding exclusive | |
| 72 | + * synchronization. The {@link java.util.concurrent.locks.LockSupport} | |
| 73 | + * class provides lower-level blocking and unblocking support that is | |
| 74 | + * useful for those developers implementing their own customized lock | |
| 75 | + * classes. | |
| 76 | + * | |
| 77 | + * @since 1.5 | |
| 78 | + */ | |
| 79 | +package java.util.concurrent.locks; | |