Print this page
Split |
Close |
Expand all |
Collapse all |
--- old/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java
+++ new/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java
1 1 /*
2 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 3 *
4 4 * This code is free software; you can redistribute it and/or modify it
5 5 * under the terms of the GNU General Public License version 2 only, as
6 6 * published by the Free Software Foundation. Oracle designates this
7 7 * particular file as subject to the "Classpath" exception as provided
8 8 * by Oracle in the LICENSE file that accompanied this code.
9 9 *
10 10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 13 * version 2 for more details (a copy is included in the LICENSE file that
14 14 * accompanied this code).
15 15 *
16 16 * You should have received a copy of the GNU General Public License version
17 17 * 2 along with this work; if not, write to the Free Software Foundation,
18 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 19 *
20 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 21 * or visit www.oracle.com if you need additional information or have any
22 22 * questions.
23 23 */
24 24
25 25 /*
26 26 * This file is available under and governed by the GNU General Public
27 27 * License version 2 only, as published by the Free Software Foundation.
28 28 * However, the following notice accompanied the original version of this
29 29 * file:
30 30 *
31 31 * Written by Doug Lea with assistance from members of JCP JSR-166
32 32 * Expert Group and released to the public domain, as explained at
33 33 * http://creativecommons.org/licenses/publicdomain
34 34 */
35 35
36 36 package java.util.concurrent.locks;
37 37 import java.util.concurrent.*;
38 38 import java.util.concurrent.atomic.*;
39 39 import java.util.*;
40 40
41 41 /**
42 42 * An implementation of {@link ReadWriteLock} supporting similar
43 43 * semantics to {@link ReentrantLock}.
44 44 * <p>This class has the following properties:
45 45 *
46 46 * <ul>
47 47 * <li><b>Acquisition order</b>
48 48 *
49 49 * <p> This class does not impose a reader or writer preference
50 50 * ordering for lock access. However, it does support an optional
51 51 * <em>fairness</em> policy.
52 52 *
53 53 * <dl>
54 54 * <dt><b><i>Non-fair mode (default)</i></b>
55 55 * <dd>When constructed as non-fair (the default), the order of entry
56 56 * to the read and write lock is unspecified, subject to reentrancy
57 57 * constraints. A nonfair lock that is continuously contended may
58 58 * indefinitely postpone one or more reader or writer threads, but
59 59 * will normally have higher throughput than a fair lock.
60 60 * <p>
61 61 *
62 62 * <dt><b><i>Fair mode</i></b>
63 63 * <dd> When constructed as fair, threads contend for entry using an
64 64 * approximately arrival-order policy. When the currently held lock
65 65 * is released either the longest-waiting single writer thread will
66 66 * be assigned the write lock, or if there is a group of reader threads
67 67 * waiting longer than all waiting writer threads, that group will be
68 68 * assigned the read lock.
69 69 *
70 70 * <p>A thread that tries to acquire a fair read lock (non-reentrantly)
71 71 * will block if either the write lock is held, or there is a waiting
72 72 * writer thread. The thread will not acquire the read lock until
73 73 * after the oldest currently waiting writer thread has acquired and
74 74 * released the write lock. Of course, if a waiting writer abandons
75 75 * its wait, leaving one or more reader threads as the longest waiters
76 76 * in the queue with the write lock free, then those readers will be
77 77 * assigned the read lock.
78 78 *
79 79 * <p>A thread that tries to acquire a fair write lock (non-reentrantly)
80 80 * will block unless both the read lock and write lock are free (which
81 81 * implies there are no waiting threads). (Note that the non-blocking
82 82 * {@link ReadLock#tryLock()} and {@link WriteLock#tryLock()} methods
83 83 * do not honor this fair setting and will acquire the lock if it is
84 84 * possible, regardless of waiting threads.)
85 85 * <p>
86 86 * </dl>
87 87 *
88 88 * <li><b>Reentrancy</b>
89 89 *
90 90 * <p>This lock allows both readers and writers to reacquire read or
91 91 * write locks in the style of a {@link ReentrantLock}. Non-reentrant
92 92 * readers are not allowed until all write locks held by the writing
93 93 * thread have been released.
94 94 *
95 95 * <p>Additionally, a writer can acquire the read lock, but not
96 96 * vice-versa. Among other applications, reentrancy can be useful
97 97 * when write locks are held during calls or callbacks to methods that
98 98 * perform reads under read locks. If a reader tries to acquire the
99 99 * write lock it will never succeed.
100 100 *
101 101 * <li><b>Lock downgrading</b>
102 102 * <p>Reentrancy also allows downgrading from the write lock to a read lock,
103 103 * by acquiring the write lock, then the read lock and then releasing the
104 104 * write lock. However, upgrading from a read lock to the write lock is
105 105 * <b>not</b> possible.
106 106 *
107 107 * <li><b>Interruption of lock acquisition</b>
108 108 * <p>The read lock and write lock both support interruption during lock
109 109 * acquisition.
110 110 *
111 111 * <li><b>{@link Condition} support</b>
112 112 * <p>The write lock provides a {@link Condition} implementation that
113 113 * behaves in the same way, with respect to the write lock, as the
114 114 * {@link Condition} implementation provided by
115 115 * {@link ReentrantLock#newCondition} does for {@link ReentrantLock}.
116 116 * This {@link Condition} can, of course, only be used with the write lock.
117 117 *
118 118 * <p>The read lock does not support a {@link Condition} and
119 119 * {@code readLock().newCondition()} throws
120 120 * {@code UnsupportedOperationException}.
121 121 *
122 122 * <li><b>Instrumentation</b>
123 123 * <p>This class supports methods to determine whether locks
124 124 * are held or contended. These methods are designed for monitoring
125 125 * system state, not for synchronization control.
126 126 * </ul>
127 127 *
128 128 * <p>Serialization of this class behaves in the same way as built-in
129 129 * locks: a deserialized lock is in the unlocked state, regardless of
130 130 * its state when serialized.
131 131 *
132 132 * <p><b>Sample usages</b>. Here is a code sketch showing how to perform
133 133 * lock downgrading after updating a cache (exception handling is
134 134 * particularly tricky when handling multiple locks in a non-nested
135 135 * fashion):
136 136 *
137 137 * <pre> {@code
138 138 * class CachedData {
139 139 * Object data;
140 140 * volatile boolean cacheValid;
141 141 * final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
142 142 *
143 143 * void processCachedData() {
144 144 * rwl.readLock().lock();
145 145 * if (!cacheValid) {
146 146 * // Must release read lock before acquiring write lock
147 147 * rwl.readLock().unlock();
↓ open down ↓ |
147 lines elided |
↑ open up ↑ |
148 148 * rwl.writeLock().lock();
149 149 * try {
150 150 * // Recheck state because another thread might have
151 151 * // acquired write lock and changed state before we did.
152 152 * if (!cacheValid) {
153 153 * data = ...
154 154 * cacheValid = true;
155 155 * }
156 156 * // Downgrade by acquiring read lock before releasing write lock
157 157 * rwl.readLock().lock();
158 - * } finally {
158 + * } finally {
159 159 * rwl.writeLock().unlock(); // Unlock write, still hold read
160 160 * }
161 161 * }
162 162 *
163 163 * try {
164 164 * use(data);
165 165 * } finally {
166 166 * rwl.readLock().unlock();
167 167 * }
168 168 * }
169 169 * }}</pre>
170 170 *
171 171 * ReentrantReadWriteLocks can be used to improve concurrency in some
172 172 * uses of some kinds of Collections. This is typically worthwhile
173 173 * only when the collections are expected to be large, accessed by
174 174 * more reader threads than writer threads, and entail operations with
175 175 * overhead that outweighs synchronization overhead. For example, here
176 176 * is a class using a TreeMap that is expected to be large and
177 177 * concurrently accessed.
178 178 *
179 179 * <pre>{@code
180 180 * class RWDictionary {
181 181 * private final Map<String, Data> m = new TreeMap<String, Data>();
182 182 * private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
183 183 * private final Lock r = rwl.readLock();
184 184 * private final Lock w = rwl.writeLock();
185 185 *
186 186 * public Data get(String key) {
187 187 * r.lock();
188 188 * try { return m.get(key); }
189 189 * finally { r.unlock(); }
190 190 * }
191 191 * public String[] allKeys() {
192 192 * r.lock();
193 193 * try { return m.keySet().toArray(); }
194 194 * finally { r.unlock(); }
195 195 * }
196 196 * public Data put(String key, Data value) {
197 197 * w.lock();
198 198 * try { return m.put(key, value); }
199 199 * finally { w.unlock(); }
200 200 * }
201 201 * public void clear() {
202 202 * w.lock();
203 203 * try { m.clear(); }
204 204 * finally { w.unlock(); }
205 205 * }
206 206 * }}</pre>
207 207 *
↓ open down ↓ |
39 lines elided |
↑ open up ↑ |
208 208 * <h3>Implementation Notes</h3>
209 209 *
210 210 * <p>This lock supports a maximum of 65535 recursive write locks
211 211 * and 65535 read locks. Attempts to exceed these limits result in
212 212 * {@link Error} throws from locking methods.
213 213 *
214 214 * @since 1.5
215 215 * @author Doug Lea
216 216 *
217 217 */
218 -public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializable {
218 +public class ReentrantReadWriteLock
219 + implements ReadWriteLock, java.io.Serializable {
219 220 private static final long serialVersionUID = -6992448646407690164L;
220 221 /** Inner class providing readlock */
221 222 private final ReentrantReadWriteLock.ReadLock readerLock;
222 223 /** Inner class providing writelock */
223 224 private final ReentrantReadWriteLock.WriteLock writerLock;
224 225 /** Performs all synchronization mechanics */
225 226 final Sync sync;
226 227
227 228 /**
228 229 * Creates a new {@code ReentrantReadWriteLock} with
229 230 * default (nonfair) ordering properties.
230 231 */
231 232 public ReentrantReadWriteLock() {
232 233 this(false);
233 234 }
234 235
235 236 /**
236 237 * Creates a new {@code ReentrantReadWriteLock} with
237 238 * the given fairness policy.
238 239 *
239 240 * @param fair {@code true} if this lock should use a fair ordering policy
240 241 */
241 242 public ReentrantReadWriteLock(boolean fair) {
242 243 sync = fair ? new FairSync() : new NonfairSync();
243 244 readerLock = new ReadLock(this);
↓ open down ↓ |
15 lines elided |
↑ open up ↑ |
244 245 writerLock = new WriteLock(this);
245 246 }
246 247
247 248 public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; }
248 249 public ReentrantReadWriteLock.ReadLock readLock() { return readerLock; }
249 250
250 251 /**
251 252 * Synchronization implementation for ReentrantReadWriteLock.
252 253 * Subclassed into fair and nonfair versions.
253 254 */
254 - static abstract class Sync extends AbstractQueuedSynchronizer {
255 + abstract static class Sync extends AbstractQueuedSynchronizer {
255 256 private static final long serialVersionUID = 6317671515068378041L;
256 257
257 258 /*
258 259 * Read vs write count extraction constants and functions.
259 260 * Lock state is logically divided into two unsigned shorts:
260 261 * The lower one representing the exclusive (writer) lock hold count,
261 262 * and the upper the shared (reader) hold count.
262 263 */
263 264
264 265 static final int SHARED_SHIFT = 16;
265 266 static final int SHARED_UNIT = (1 << SHARED_SHIFT);
266 267 static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1;
267 268 static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
268 269
269 270 /** Returns the number of shared holds represented in count */
270 271 static int sharedCount(int c) { return c >>> SHARED_SHIFT; }
271 272 /** Returns the number of exclusive holds represented in count */
272 273 static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
273 274
274 275 /**
275 276 * A counter for per-thread read hold counts.
276 277 * Maintained as a ThreadLocal; cached in cachedHoldCounter
277 278 */
278 279 static final class HoldCounter {
279 280 int count = 0;
280 281 // Use id, not reference, to avoid garbage retention
281 282 final long tid = Thread.currentThread().getId();
282 283 }
283 284
284 285 /**
285 286 * ThreadLocal subclass. Easiest to explicitly define for sake
286 287 * of deserialization mechanics.
287 288 */
288 289 static final class ThreadLocalHoldCounter
289 290 extends ThreadLocal<HoldCounter> {
290 291 public HoldCounter initialValue() {
291 292 return new HoldCounter();
292 293 }
293 294 }
294 295
295 296 /**
296 297 * The number of reentrant read locks held by current thread.
297 298 * Initialized only in constructor and readObject.
298 299 * Removed whenever a thread's read hold count drops to 0.
299 300 */
300 301 private transient ThreadLocalHoldCounter readHolds;
301 302
302 303 /**
303 304 * The hold count of the last thread to successfully acquire
304 305 * readLock. This saves ThreadLocal lookup in the common case
305 306 * where the next thread to release is the last one to
306 307 * acquire. This is non-volatile since it is just used
307 308 * as a heuristic, and would be great for threads to cache.
308 309 *
309 310 * <p>Can outlive the Thread for which it is caching the read
310 311 * hold count, but avoids garbage retention by not retaining a
311 312 * reference to the Thread.
312 313 *
313 314 * <p>Accessed via a benign data race; relies on the memory
314 315 * model's final field and out-of-thin-air guarantees.
315 316 */
316 317 private transient HoldCounter cachedHoldCounter;
317 318
318 319 /**
319 320 * firstReader is the first thread to have acquired the read lock.
320 321 * firstReaderHoldCount is firstReader's hold count.
321 322 *
322 323 * <p>More precisely, firstReader is the unique thread that last
323 324 * changed the shared count from 0 to 1, and has not released the
324 325 * read lock since then; null if there is no such thread.
325 326 *
326 327 * <p>Cannot cause garbage retention unless the thread terminated
327 328 * without relinquishing its read locks, since tryReleaseShared
328 329 * sets it to null.
329 330 *
330 331 * <p>Accessed via a benign data race; relies on the memory
331 332 * model's out-of-thin-air guarantees for references.
332 333 *
333 334 * <p>This allows tracking of read holds for uncontended read
334 335 * locks to be very cheap.
335 336 */
336 337 private transient Thread firstReader = null;
337 338 private transient int firstReaderHoldCount;
338 339
339 340 Sync() {
340 341 readHolds = new ThreadLocalHoldCounter();
341 342 setState(getState()); // ensures visibility of readHolds
342 343 }
343 344
344 345 /*
345 346 * Acquires and releases use the same code for fair and
346 347 * nonfair locks, but differ in whether/how they allow barging
347 348 * when queues are non-empty.
348 349 */
349 350
350 351 /**
351 352 * Returns true if the current thread, when trying to acquire
352 353 * the read lock, and otherwise eligible to do so, should block
353 354 * because of policy for overtaking other waiting threads.
354 355 */
355 356 abstract boolean readerShouldBlock();
356 357
357 358 /**
358 359 * Returns true if the current thread, when trying to acquire
359 360 * the write lock, and otherwise eligible to do so, should block
360 361 * because of policy for overtaking other waiting threads.
361 362 */
362 363 abstract boolean writerShouldBlock();
363 364
364 365 /*
365 366 * Note that tryRelease and tryAcquire can be called by
366 367 * Conditions. So it is possible that their arguments contain
367 368 * both read and write holds that are all released during a
368 369 * condition wait and re-established in tryAcquire.
369 370 */
370 371
371 372 protected final boolean tryRelease(int releases) {
372 373 if (!isHeldExclusively())
373 374 throw new IllegalMonitorStateException();
374 375 int nextc = getState() - releases;
375 376 boolean free = exclusiveCount(nextc) == 0;
376 377 if (free)
377 378 setExclusiveOwnerThread(null);
378 379 setState(nextc);
379 380 return free;
380 381 }
381 382
382 383 protected final boolean tryAcquire(int acquires) {
383 384 /*
384 385 * Walkthrough:
385 386 * 1. If read count nonzero or write count nonzero
386 387 * and owner is a different thread, fail.
387 388 * 2. If count would saturate, fail. (This can only
388 389 * happen if count is already nonzero.)
389 390 * 3. Otherwise, this thread is eligible for lock if
390 391 * it is either a reentrant acquire or
391 392 * queue policy allows it. If so, update state
392 393 * and set owner.
393 394 */
394 395 Thread current = Thread.currentThread();
395 396 int c = getState();
396 397 int w = exclusiveCount(c);
397 398 if (c != 0) {
398 399 // (Note: if c != 0 and w == 0 then shared count != 0)
399 400 if (w == 0 || current != getExclusiveOwnerThread())
400 401 return false;
401 402 if (w + exclusiveCount(acquires) > MAX_COUNT)
402 403 throw new Error("Maximum lock count exceeded");
403 404 // Reentrant acquire
404 405 setState(c + acquires);
405 406 return true;
406 407 }
407 408 if (writerShouldBlock() ||
408 409 !compareAndSetState(c, c + acquires))
409 410 return false;
410 411 setExclusiveOwnerThread(current);
411 412 return true;
412 413 }
413 414
414 415 protected final boolean tryReleaseShared(int unused) {
415 416 Thread current = Thread.currentThread();
416 417 if (firstReader == current) {
417 418 // assert firstReaderHoldCount > 0;
418 419 if (firstReaderHoldCount == 1)
419 420 firstReader = null;
420 421 else
421 422 firstReaderHoldCount--;
422 423 } else {
423 424 HoldCounter rh = cachedHoldCounter;
424 425 if (rh == null || rh.tid != current.getId())
425 426 rh = readHolds.get();
426 427 int count = rh.count;
427 428 if (count <= 1) {
428 429 readHolds.remove();
429 430 if (count <= 0)
430 431 throw unmatchedUnlockException();
431 432 }
432 433 --rh.count;
433 434 }
434 435 for (;;) {
435 436 int c = getState();
436 437 int nextc = c - SHARED_UNIT;
437 438 if (compareAndSetState(c, nextc))
438 439 // Releasing the read lock has no effect on readers,
439 440 // but it may allow waiting writers to proceed if
440 441 // both read and write locks are now free.
441 442 return nextc == 0;
442 443 }
443 444 }
444 445
445 446 private IllegalMonitorStateException unmatchedUnlockException() {
446 447 return new IllegalMonitorStateException(
447 448 "attempt to unlock read lock, not locked by current thread");
448 449 }
449 450
450 451 protected final int tryAcquireShared(int unused) {
451 452 /*
452 453 * Walkthrough:
453 454 * 1. If write lock held by another thread, fail.
454 455 * 2. Otherwise, this thread is eligible for
455 456 * lock wrt state, so ask if it should block
456 457 * because of queue policy. If not, try
457 458 * to grant by CASing state and updating count.
458 459 * Note that step does not check for reentrant
459 460 * acquires, which is postponed to full version
460 461 * to avoid having to check hold count in
461 462 * the more typical non-reentrant case.
462 463 * 3. If step 2 fails either because thread
463 464 * apparently not eligible or CAS fails or count
464 465 * saturated, chain to version with full retry loop.
465 466 */
466 467 Thread current = Thread.currentThread();
467 468 int c = getState();
468 469 if (exclusiveCount(c) != 0 &&
469 470 getExclusiveOwnerThread() != current)
470 471 return -1;
471 472 int r = sharedCount(c);
472 473 if (!readerShouldBlock() &&
473 474 r < MAX_COUNT &&
474 475 compareAndSetState(c, c + SHARED_UNIT)) {
475 476 if (r == 0) {
476 477 firstReader = current;
477 478 firstReaderHoldCount = 1;
478 479 } else if (firstReader == current) {
479 480 firstReaderHoldCount++;
480 481 } else {
481 482 HoldCounter rh = cachedHoldCounter;
482 483 if (rh == null || rh.tid != current.getId())
483 484 cachedHoldCounter = rh = readHolds.get();
484 485 else if (rh.count == 0)
485 486 readHolds.set(rh);
486 487 rh.count++;
487 488 }
488 489 return 1;
489 490 }
490 491 return fullTryAcquireShared(current);
491 492 }
492 493
493 494 /**
494 495 * Full version of acquire for reads, that handles CAS misses
495 496 * and reentrant reads not dealt with in tryAcquireShared.
496 497 */
497 498 final int fullTryAcquireShared(Thread current) {
498 499 /*
499 500 * This code is in part redundant with that in
500 501 * tryAcquireShared but is simpler overall by not
501 502 * complicating tryAcquireShared with interactions between
502 503 * retries and lazily reading hold counts.
503 504 */
504 505 HoldCounter rh = null;
505 506 for (;;) {
506 507 int c = getState();
507 508 if (exclusiveCount(c) != 0) {
508 509 if (getExclusiveOwnerThread() != current)
509 510 return -1;
510 511 // else we hold the exclusive lock; blocking here
511 512 // would cause deadlock.
512 513 } else if (readerShouldBlock()) {
513 514 // Make sure we're not acquiring read lock reentrantly
514 515 if (firstReader == current) {
515 516 // assert firstReaderHoldCount > 0;
516 517 } else {
517 518 if (rh == null) {
518 519 rh = cachedHoldCounter;
519 520 if (rh == null || rh.tid != current.getId()) {
520 521 rh = readHolds.get();
521 522 if (rh.count == 0)
522 523 readHolds.remove();
523 524 }
524 525 }
525 526 if (rh.count == 0)
526 527 return -1;
527 528 }
528 529 }
529 530 if (sharedCount(c) == MAX_COUNT)
530 531 throw new Error("Maximum lock count exceeded");
531 532 if (compareAndSetState(c, c + SHARED_UNIT)) {
532 533 if (sharedCount(c) == 0) {
533 534 firstReader = current;
534 535 firstReaderHoldCount = 1;
535 536 } else if (firstReader == current) {
536 537 firstReaderHoldCount++;
537 538 } else {
538 539 if (rh == null)
539 540 rh = cachedHoldCounter;
540 541 if (rh == null || rh.tid != current.getId())
541 542 rh = readHolds.get();
542 543 else if (rh.count == 0)
543 544 readHolds.set(rh);
544 545 rh.count++;
545 546 cachedHoldCounter = rh; // cache for release
546 547 }
547 548 return 1;
548 549 }
549 550 }
550 551 }
551 552
552 553 /**
553 554 * Performs tryLock for write, enabling barging in both modes.
554 555 * This is identical in effect to tryAcquire except for lack
555 556 * of calls to writerShouldBlock.
556 557 */
557 558 final boolean tryWriteLock() {
558 559 Thread current = Thread.currentThread();
559 560 int c = getState();
560 561 if (c != 0) {
561 562 int w = exclusiveCount(c);
562 563 if (w == 0 || current != getExclusiveOwnerThread())
563 564 return false;
564 565 if (w == MAX_COUNT)
565 566 throw new Error("Maximum lock count exceeded");
566 567 }
567 568 if (!compareAndSetState(c, c + 1))
568 569 return false;
569 570 setExclusiveOwnerThread(current);
570 571 return true;
571 572 }
572 573
573 574 /**
574 575 * Performs tryLock for read, enabling barging in both modes.
575 576 * This is identical in effect to tryAcquireShared except for
576 577 * lack of calls to readerShouldBlock.
577 578 */
578 579 final boolean tryReadLock() {
579 580 Thread current = Thread.currentThread();
580 581 for (;;) {
581 582 int c = getState();
582 583 if (exclusiveCount(c) != 0 &&
583 584 getExclusiveOwnerThread() != current)
584 585 return false;
585 586 int r = sharedCount(c);
586 587 if (r == MAX_COUNT)
587 588 throw new Error("Maximum lock count exceeded");
588 589 if (compareAndSetState(c, c + SHARED_UNIT)) {
589 590 if (r == 0) {
590 591 firstReader = current;
591 592 firstReaderHoldCount = 1;
592 593 } else if (firstReader == current) {
593 594 firstReaderHoldCount++;
594 595 } else {
595 596 HoldCounter rh = cachedHoldCounter;
596 597 if (rh == null || rh.tid != current.getId())
597 598 cachedHoldCounter = rh = readHolds.get();
598 599 else if (rh.count == 0)
599 600 readHolds.set(rh);
600 601 rh.count++;
601 602 }
602 603 return true;
603 604 }
604 605 }
605 606 }
606 607
607 608 protected final boolean isHeldExclusively() {
608 609 // While we must in general read state before owner,
609 610 // we don't need to do so to check if current thread is owner
610 611 return getExclusiveOwnerThread() == Thread.currentThread();
↓ open down ↓ |
346 lines elided |
↑ open up ↑ |
611 612 }
612 613
613 614 // Methods relayed to outer class
614 615
615 616 final ConditionObject newCondition() {
616 617 return new ConditionObject();
617 618 }
618 619
619 620 final Thread getOwner() {
620 621 // Must read state before owner to ensure memory consistency
621 - return ((exclusiveCount(getState()) == 0)?
622 + return ((exclusiveCount(getState()) == 0) ?
622 623 null :
623 624 getExclusiveOwnerThread());
624 625 }
625 626
626 627 final int getReadLockCount() {
627 628 return sharedCount(getState());
628 629 }
629 630
630 631 final boolean isWriteLocked() {
631 632 return exclusiveCount(getState()) != 0;
632 633 }
633 634
634 635 final int getWriteHoldCount() {
635 636 return isHeldExclusively() ? exclusiveCount(getState()) : 0;
636 637 }
637 638
638 639 final int getReadHoldCount() {
639 640 if (getReadLockCount() == 0)
640 641 return 0;
641 642
642 643 Thread current = Thread.currentThread();
643 644 if (firstReader == current)
644 645 return firstReaderHoldCount;
645 646
646 647 HoldCounter rh = cachedHoldCounter;
647 648 if (rh != null && rh.tid == current.getId())
648 649 return rh.count;
649 650
650 651 int count = readHolds.get().count;
651 652 if (count == 0) readHolds.remove();
652 653 return count;
653 654 }
654 655
655 656 /**
656 657 * Reconstitute this lock instance from a stream
657 658 * @param s the stream
658 659 */
659 660 private void readObject(java.io.ObjectInputStream s)
660 661 throws java.io.IOException, ClassNotFoundException {
661 662 s.defaultReadObject();
↓ open down ↓ |
30 lines elided |
↑ open up ↑ |
662 663 readHolds = new ThreadLocalHoldCounter();
663 664 setState(0); // reset to unlocked state
664 665 }
665 666
666 667 final int getCount() { return getState(); }
667 668 }
668 669
669 670 /**
670 671 * Nonfair version of Sync
671 672 */
672 - final static class NonfairSync extends Sync {
673 + static final class NonfairSync extends Sync {
673 674 private static final long serialVersionUID = -8159625535654395037L;
674 675 final boolean writerShouldBlock() {
675 676 return false; // writers can always barge
676 677 }
677 678 final boolean readerShouldBlock() {
678 679 /* As a heuristic to avoid indefinite writer starvation,
679 680 * block if the thread that momentarily appears to be head
680 681 * of queue, if one exists, is a waiting writer. This is
681 682 * only a probabilistic effect since a new reader will not
682 683 * block if there is a waiting writer behind other enabled
683 684 * readers that have not yet drained from the queue.
684 685 */
685 686 return apparentlyFirstQueuedIsExclusive();
686 687 }
687 688 }
688 689
689 690 /**
690 691 * Fair version of Sync
691 692 */
692 - final static class FairSync extends Sync {
693 + static final class FairSync extends Sync {
693 694 private static final long serialVersionUID = -2274990926593161451L;
694 695 final boolean writerShouldBlock() {
695 696 return hasQueuedPredecessors();
696 697 }
697 698 final boolean readerShouldBlock() {
698 699 return hasQueuedPredecessors();
699 700 }
700 701 }
701 702
702 703 /**
703 704 * The lock returned by method {@link ReentrantReadWriteLock#readLock}.
704 705 */
705 - public static class ReadLock implements Lock, java.io.Serializable {
706 + public static class ReadLock implements Lock, java.io.Serializable {
706 707 private static final long serialVersionUID = -5992448646407690164L;
707 708 private final Sync sync;
708 709
709 710 /**
710 711 * Constructor for use by subclasses
711 712 *
712 713 * @param lock the outer lock object
713 714 * @throws NullPointerException if the lock is null
714 715 */
715 716 protected ReadLock(ReentrantReadWriteLock lock) {
716 717 sync = lock.sync;
717 718 }
718 719
719 720 /**
720 721 * Acquires the read lock.
721 722 *
722 723 * <p>Acquires the read lock if the write lock is not held by
723 724 * another thread and returns immediately.
724 725 *
725 726 * <p>If the write lock is held by another thread then
726 727 * the current thread becomes disabled for thread scheduling
727 728 * purposes and lies dormant until the read lock has been acquired.
728 729 */
729 730 public void lock() {
730 731 sync.acquireShared(1);
731 732 }
732 733
733 734 /**
734 735 * Acquires the read lock unless the current thread is
735 736 * {@linkplain Thread#interrupt interrupted}.
736 737 *
737 738 * <p>Acquires the read lock if the write lock is not held
738 739 * by another thread and returns immediately.
739 740 *
740 741 * <p>If the write lock is held by another thread then the
741 742 * current thread becomes disabled for thread scheduling
742 743 * purposes and lies dormant until one of two things happens:
743 744 *
744 745 * <ul>
745 746 *
746 747 * <li>The read lock is acquired by the current thread; or
747 748 *
748 749 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
749 750 * the current thread.
750 751 *
751 752 * </ul>
752 753 *
753 754 * <p>If the current thread:
754 755 *
755 756 * <ul>
756 757 *
757 758 * <li>has its interrupted status set on entry to this method; or
758 759 *
759 760 * <li>is {@linkplain Thread#interrupt interrupted} while
760 761 * acquiring the read lock,
761 762 *
762 763 * </ul>
763 764 *
764 765 * then {@link InterruptedException} is thrown and the current
765 766 * thread's interrupted status is cleared.
766 767 *
767 768 * <p>In this implementation, as this method is an explicit
768 769 * interruption point, preference is given to responding to
769 770 * the interrupt over normal or reentrant acquisition of the
770 771 * lock.
771 772 *
772 773 * @throws InterruptedException if the current thread is interrupted
773 774 */
774 775 public void lockInterruptibly() throws InterruptedException {
775 776 sync.acquireSharedInterruptibly(1);
776 777 }
777 778
778 779 /**
779 780 * Acquires the read lock only if the write lock is not held by
780 781 * another thread at the time of invocation.
781 782 *
782 783 * <p>Acquires the read lock if the write lock is not held by
783 784 * another thread and returns immediately with the value
784 785 * {@code true}. Even when this lock has been set to use a
785 786 * fair ordering policy, a call to {@code tryLock()}
786 787 * <em>will</em> immediately acquire the read lock if it is
787 788 * available, whether or not other threads are currently
788 789 * waiting for the read lock. This "barging" behavior
789 790 * can be useful in certain circumstances, even though it
790 791 * breaks fairness. If you want to honor the fairness setting
791 792 * for this lock, then use {@link #tryLock(long, TimeUnit)
792 793 * tryLock(0, TimeUnit.SECONDS) } which is almost equivalent
793 794 * (it also detects interruption).
794 795 *
795 796 * <p>If the write lock is held by another thread then
796 797 * this method will return immediately with the value
797 798 * {@code false}.
798 799 *
799 800 * @return {@code true} if the read lock was acquired
800 801 */
801 802 public boolean tryLock() {
802 803 return sync.tryReadLock();
803 804 }
804 805
805 806 /**
806 807 * Acquires the read lock if the write lock is not held by
807 808 * another thread within the given waiting time and the
808 809 * current thread has not been {@linkplain Thread#interrupt
809 810 * interrupted}.
810 811 *
811 812 * <p>Acquires the read lock if the write lock is not held by
812 813 * another thread and returns immediately with the value
813 814 * {@code true}. If this lock has been set to use a fair
814 815 * ordering policy then an available lock <em>will not</em> be
815 816 * acquired if any other threads are waiting for the
816 817 * lock. This is in contrast to the {@link #tryLock()}
817 818 * method. If you want a timed {@code tryLock} that does
818 819 * permit barging on a fair lock then combine the timed and
819 820 * un-timed forms together:
820 821 *
821 822 * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
822 823 * </pre>
823 824 *
824 825 * <p>If the write lock is held by another thread then the
825 826 * current thread becomes disabled for thread scheduling
826 827 * purposes and lies dormant until one of three things happens:
827 828 *
828 829 * <ul>
829 830 *
830 831 * <li>The read lock is acquired by the current thread; or
831 832 *
832 833 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
833 834 * the current thread; or
834 835 *
835 836 * <li>The specified waiting time elapses.
836 837 *
837 838 * </ul>
838 839 *
839 840 * <p>If the read lock is acquired then the value {@code true} is
840 841 * returned.
841 842 *
842 843 * <p>If the current thread:
843 844 *
844 845 * <ul>
845 846 *
846 847 * <li>has its interrupted status set on entry to this method; or
847 848 *
848 849 * <li>is {@linkplain Thread#interrupt interrupted} while
849 850 * acquiring the read lock,
850 851 *
851 852 * </ul> then {@link InterruptedException} is thrown and the
852 853 * current thread's interrupted status is cleared.
853 854 *
854 855 * <p>If the specified waiting time elapses then the value
855 856 * {@code false} is returned. If the time is less than or
856 857 * equal to zero, the method will not wait at all.
857 858 *
858 859 * <p>In this implementation, as this method is an explicit
859 860 * interruption point, preference is given to responding to
↓ open down ↓ |
144 lines elided |
↑ open up ↑ |
860 861 * the interrupt over normal or reentrant acquisition of the
861 862 * lock, and over reporting the elapse of the waiting time.
862 863 *
863 864 * @param timeout the time to wait for the read lock
864 865 * @param unit the time unit of the timeout argument
865 866 * @return {@code true} if the read lock was acquired
866 867 * @throws InterruptedException if the current thread is interrupted
867 868 * @throws NullPointerException if the time unit is null
868 869 *
869 870 */
870 - public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
871 + public boolean tryLock(long timeout, TimeUnit unit)
872 + throws InterruptedException {
871 873 return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
872 874 }
873 875
874 876 /**
875 877 * Attempts to release this lock.
876 878 *
877 879 * <p> If the number of readers is now zero then the lock
878 880 * is made available for write lock attempts.
879 881 */
880 882 public void unlock() {
881 883 sync.releaseShared(1);
882 884 }
883 885
884 886 /**
885 887 * Throws {@code UnsupportedOperationException} because
886 888 * {@code ReadLocks} do not support conditions.
887 889 *
888 890 * @throws UnsupportedOperationException always
889 891 */
890 892 public Condition newCondition() {
891 893 throw new UnsupportedOperationException();
892 894 }
893 895
894 896 /**
895 897 * Returns a string identifying this lock, as well as its lock state.
896 898 * The state, in brackets, includes the String {@code "Read locks ="}
897 899 * followed by the number of held read locks.
898 900 *
899 901 * @return a string identifying this lock, as well as its lock state
900 902 */
↓ open down ↓ |
20 lines elided |
↑ open up ↑ |
901 903 public String toString() {
902 904 int r = sync.getReadLockCount();
903 905 return super.toString() +
904 906 "[Read locks = " + r + "]";
905 907 }
906 908 }
907 909
908 910 /**
909 911 * The lock returned by method {@link ReentrantReadWriteLock#writeLock}.
910 912 */
911 - public static class WriteLock implements Lock, java.io.Serializable {
913 + public static class WriteLock implements Lock, java.io.Serializable {
912 914 private static final long serialVersionUID = -4992448646407690164L;
913 915 private final Sync sync;
914 916
915 917 /**
916 918 * Constructor for use by subclasses
917 919 *
918 920 * @param lock the outer lock object
919 921 * @throws NullPointerException if the lock is null
920 922 */
921 923 protected WriteLock(ReentrantReadWriteLock lock) {
922 924 sync = lock.sync;
923 925 }
924 926
925 927 /**
926 928 * Acquires the write lock.
927 929 *
928 930 * <p>Acquires the write lock if neither the read nor write lock
929 931 * are held by another thread
930 932 * and returns immediately, setting the write lock hold count to
931 933 * one.
932 934 *
933 935 * <p>If the current thread already holds the write lock then the
934 936 * hold count is incremented by one and the method returns
935 937 * immediately.
936 938 *
937 939 * <p>If the lock is held by another thread then the current
938 940 * thread becomes disabled for thread scheduling purposes and
939 941 * lies dormant until the write lock has been acquired, at which
940 942 * time the write lock hold count is set to one.
941 943 */
942 944 public void lock() {
943 945 sync.acquire(1);
944 946 }
945 947
946 948 /**
947 949 * Acquires the write lock unless the current thread is
948 950 * {@linkplain Thread#interrupt interrupted}.
949 951 *
950 952 * <p>Acquires the write lock if neither the read nor write lock
951 953 * are held by another thread
952 954 * and returns immediately, setting the write lock hold count to
953 955 * one.
954 956 *
955 957 * <p>If the current thread already holds this lock then the
956 958 * hold count is incremented by one and the method returns
957 959 * immediately.
958 960 *
959 961 * <p>If the lock is held by another thread then the current
960 962 * thread becomes disabled for thread scheduling purposes and
961 963 * lies dormant until one of two things happens:
962 964 *
963 965 * <ul>
964 966 *
965 967 * <li>The write lock is acquired by the current thread; or
966 968 *
967 969 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
968 970 * the current thread.
969 971 *
970 972 * </ul>
971 973 *
972 974 * <p>If the write lock is acquired by the current thread then the
973 975 * lock hold count is set to one.
974 976 *
975 977 * <p>If the current thread:
976 978 *
977 979 * <ul>
978 980 *
979 981 * <li>has its interrupted status set on entry to this method;
980 982 * or
981 983 *
982 984 * <li>is {@linkplain Thread#interrupt interrupted} while
983 985 * acquiring the write lock,
984 986 *
985 987 * </ul>
986 988 *
987 989 * then {@link InterruptedException} is thrown and the current
988 990 * thread's interrupted status is cleared.
989 991 *
990 992 * <p>In this implementation, as this method is an explicit
991 993 * interruption point, preference is given to responding to
992 994 * the interrupt over normal or reentrant acquisition of the
993 995 * lock.
994 996 *
995 997 * @throws InterruptedException if the current thread is interrupted
996 998 */
997 999 public void lockInterruptibly() throws InterruptedException {
998 1000 sync.acquireInterruptibly(1);
999 1001 }
1000 1002
1001 1003 /**
1002 1004 * Acquires the write lock only if it is not held by another thread
1003 1005 * at the time of invocation.
1004 1006 *
1005 1007 * <p>Acquires the write lock if neither the read nor write lock
1006 1008 * are held by another thread
1007 1009 * and returns immediately with the value {@code true},
1008 1010 * setting the write lock hold count to one. Even when this lock has
1009 1011 * been set to use a fair ordering policy, a call to
1010 1012 * {@code tryLock()} <em>will</em> immediately acquire the
1011 1013 * lock if it is available, whether or not other threads are
1012 1014 * currently waiting for the write lock. This "barging"
1013 1015 * behavior can be useful in certain circumstances, even
1014 1016 * though it breaks fairness. If you want to honor the
1015 1017 * fairness setting for this lock, then use {@link
1016 1018 * #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
1017 1019 * which is almost equivalent (it also detects interruption).
1018 1020 *
1019 1021 * <p> If the current thread already holds this lock then the
1020 1022 * hold count is incremented by one and the method returns
1021 1023 * {@code true}.
1022 1024 *
1023 1025 * <p>If the lock is held by another thread then this method
1024 1026 * will return immediately with the value {@code false}.
1025 1027 *
1026 1028 * @return {@code true} if the lock was free and was acquired
1027 1029 * by the current thread, or the write lock was already held
1028 1030 * by the current thread; and {@code false} otherwise.
1029 1031 */
1030 1032 public boolean tryLock( ) {
1031 1033 return sync.tryWriteLock();
1032 1034 }
1033 1035
1034 1036 /**
1035 1037 * Acquires the write lock if it is not held by another thread
1036 1038 * within the given waiting time and the current thread has
1037 1039 * not been {@linkplain Thread#interrupt interrupted}.
1038 1040 *
1039 1041 * <p>Acquires the write lock if neither the read nor write lock
1040 1042 * are held by another thread
1041 1043 * and returns immediately with the value {@code true},
1042 1044 * setting the write lock hold count to one. If this lock has been
1043 1045 * set to use a fair ordering policy then an available lock
1044 1046 * <em>will not</em> be acquired if any other threads are
1045 1047 * waiting for the write lock. This is in contrast to the {@link
1046 1048 * #tryLock()} method. If you want a timed {@code tryLock}
1047 1049 * that does permit barging on a fair lock then combine the
1048 1050 * timed and un-timed forms together:
1049 1051 *
1050 1052 * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
1051 1053 * </pre>
1052 1054 *
1053 1055 * <p>If the current thread already holds this lock then the
1054 1056 * hold count is incremented by one and the method returns
1055 1057 * {@code true}.
1056 1058 *
1057 1059 * <p>If the lock is held by another thread then the current
1058 1060 * thread becomes disabled for thread scheduling purposes and
1059 1061 * lies dormant until one of three things happens:
1060 1062 *
1061 1063 * <ul>
1062 1064 *
1063 1065 * <li>The write lock is acquired by the current thread; or
1064 1066 *
1065 1067 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
1066 1068 * the current thread; or
1067 1069 *
1068 1070 * <li>The specified waiting time elapses
1069 1071 *
1070 1072 * </ul>
1071 1073 *
1072 1074 * <p>If the write lock is acquired then the value {@code true} is
1073 1075 * returned and the write lock hold count is set to one.
1074 1076 *
1075 1077 * <p>If the current thread:
1076 1078 *
1077 1079 * <ul>
1078 1080 *
1079 1081 * <li>has its interrupted status set on entry to this method;
1080 1082 * or
1081 1083 *
1082 1084 * <li>is {@linkplain Thread#interrupt interrupted} while
1083 1085 * acquiring the write lock,
1084 1086 *
1085 1087 * </ul>
1086 1088 *
1087 1089 * then {@link InterruptedException} is thrown and the current
1088 1090 * thread's interrupted status is cleared.
1089 1091 *
1090 1092 * <p>If the specified waiting time elapses then the value
1091 1093 * {@code false} is returned. If the time is less than or
1092 1094 * equal to zero, the method will not wait at all.
1093 1095 *
1094 1096 * <p>In this implementation, as this method is an explicit
1095 1097 * interruption point, preference is given to responding to
1096 1098 * the interrupt over normal or reentrant acquisition of the
1097 1099 * lock, and over reporting the elapse of the waiting time.
1098 1100 *
1099 1101 * @param timeout the time to wait for the write lock
1100 1102 * @param unit the time unit of the timeout argument
↓ open down ↓ |
179 lines elided |
↑ open up ↑ |
1101 1103 *
1102 1104 * @return {@code true} if the lock was free and was acquired
1103 1105 * by the current thread, or the write lock was already held by the
1104 1106 * current thread; and {@code false} if the waiting time
1105 1107 * elapsed before the lock could be acquired.
1106 1108 *
1107 1109 * @throws InterruptedException if the current thread is interrupted
1108 1110 * @throws NullPointerException if the time unit is null
1109 1111 *
1110 1112 */
1111 - public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
1113 + public boolean tryLock(long timeout, TimeUnit unit)
1114 + throws InterruptedException {
1112 1115 return sync.tryAcquireNanos(1, unit.toNanos(timeout));
1113 1116 }
1114 1117
1115 1118 /**
1116 1119 * Attempts to release this lock.
1117 1120 *
1118 1121 * <p>If the current thread is the holder of this lock then
1119 1122 * the hold count is decremented. If the hold count is now
1120 1123 * zero then the lock is released. If the current thread is
1121 1124 * not the holder of this lock then {@link
1122 1125 * IllegalMonitorStateException} is thrown.
1123 1126 *
1124 1127 * @throws IllegalMonitorStateException if the current thread does not
1125 1128 * hold this lock.
1126 1129 */
1127 1130 public void unlock() {
1128 1131 sync.release(1);
1129 1132 }
1130 1133
1131 1134 /**
1132 1135 * Returns a {@link Condition} instance for use with this
1133 1136 * {@link Lock} instance.
1134 1137 * <p>The returned {@link Condition} instance supports the same
1135 1138 * usages as do the {@link Object} monitor methods ({@link
1136 1139 * Object#wait() wait}, {@link Object#notify notify}, and {@link
1137 1140 * Object#notifyAll notifyAll}) when used with the built-in
1138 1141 * monitor lock.
1139 1142 *
1140 1143 * <ul>
1141 1144 *
1142 1145 * <li>If this write lock is not held when any {@link
1143 1146 * Condition} method is called then an {@link
1144 1147 * IllegalMonitorStateException} is thrown. (Read locks are
1145 1148 * held independently of write locks, so are not checked or
1146 1149 * affected. However it is essentially always an error to
1147 1150 * invoke a condition waiting method when the current thread
1148 1151 * has also acquired read locks, since other threads that
1149 1152 * could unblock it will not be able to acquire the write
1150 1153 * lock.)
1151 1154 *
1152 1155 * <li>When the condition {@linkplain Condition#await() waiting}
1153 1156 * methods are called the write lock is released and, before
1154 1157 * they return, the write lock is reacquired and the lock hold
1155 1158 * count restored to what it was when the method was called.
1156 1159 *
1157 1160 * <li>If a thread is {@linkplain Thread#interrupt interrupted} while
1158 1161 * waiting then the wait will terminate, an {@link
1159 1162 * InterruptedException} will be thrown, and the thread's
1160 1163 * interrupted status will be cleared.
1161 1164 *
1162 1165 * <li> Waiting threads are signalled in FIFO order.
1163 1166 *
1164 1167 * <li>The ordering of lock reacquisition for threads returning
1165 1168 * from waiting methods is the same as for threads initially
1166 1169 * acquiring the lock, which is in the default case not specified,
1167 1170 * but for <em>fair</em> locks favors those threads that have been
1168 1171 * waiting the longest.
1169 1172 *
1170 1173 * </ul>
1171 1174 *
1172 1175 * @return the Condition object
1173 1176 */
1174 1177 public Condition newCondition() {
1175 1178 return sync.newCondition();
1176 1179 }
1177 1180
1178 1181 /**
1179 1182 * Returns a string identifying this lock, as well as its lock
1180 1183 * state. The state, in brackets includes either the String
1181 1184 * {@code "Unlocked"} or the String {@code "Locked by"}
1182 1185 * followed by the {@linkplain Thread#getName name} of the owning thread.
1183 1186 *
1184 1187 * @return a string identifying this lock, as well as its lock state
1185 1188 */
1186 1189 public String toString() {
1187 1190 Thread o = sync.getOwner();
1188 1191 return super.toString() + ((o == null) ?
1189 1192 "[Unlocked]" :
1190 1193 "[Locked by thread " + o.getName() + "]");
1191 1194 }
1192 1195
1193 1196 /**
1194 1197 * Queries if this write lock is held by the current thread.
1195 1198 * Identical in effect to {@link
1196 1199 * ReentrantReadWriteLock#isWriteLockedByCurrentThread}.
1197 1200 *
1198 1201 * @return {@code true} if the current thread holds this lock and
1199 1202 * {@code false} otherwise
1200 1203 * @since 1.6
1201 1204 */
1202 1205 public boolean isHeldByCurrentThread() {
1203 1206 return sync.isHeldExclusively();
1204 1207 }
1205 1208
1206 1209 /**
1207 1210 * Queries the number of holds on this write lock by the current
1208 1211 * thread. A thread has a hold on a lock for each lock action
1209 1212 * that is not matched by an unlock action. Identical in effect
1210 1213 * to {@link ReentrantReadWriteLock#getWriteHoldCount}.
1211 1214 *
1212 1215 * @return the number of holds on this lock by the current thread,
1213 1216 * or zero if this lock is not held by the current thread
1214 1217 * @since 1.6
1215 1218 */
1216 1219 public int getHoldCount() {
1217 1220 return sync.getWriteHoldCount();
1218 1221 }
1219 1222 }
1220 1223
1221 1224 // Instrumentation and status
1222 1225
1223 1226 /**
1224 1227 * Returns {@code true} if this lock has fairness set true.
1225 1228 *
1226 1229 * @return {@code true} if this lock has fairness set true
1227 1230 */
1228 1231 public final boolean isFair() {
1229 1232 return sync instanceof FairSync;
1230 1233 }
1231 1234
1232 1235 /**
1233 1236 * Returns the thread that currently owns the write lock, or
1234 1237 * {@code null} if not owned. When this method is called by a
1235 1238 * thread that is not the owner, the return value reflects a
1236 1239 * best-effort approximation of current lock status. For example,
1237 1240 * the owner may be momentarily {@code null} even if there are
1238 1241 * threads trying to acquire the lock but have not yet done so.
1239 1242 * This method is designed to facilitate construction of
1240 1243 * subclasses that provide more extensive lock monitoring
1241 1244 * facilities.
1242 1245 *
1243 1246 * @return the owner, or {@code null} if not owned
1244 1247 */
1245 1248 protected Thread getOwner() {
1246 1249 return sync.getOwner();
1247 1250 }
1248 1251
1249 1252 /**
1250 1253 * Queries the number of read locks held for this lock. This
1251 1254 * method is designed for use in monitoring system state, not for
1252 1255 * synchronization control.
1253 1256 * @return the number of read locks held.
1254 1257 */
1255 1258 public int getReadLockCount() {
1256 1259 return sync.getReadLockCount();
1257 1260 }
1258 1261
1259 1262 /**
1260 1263 * Queries if the write lock is held by any thread. This method is
1261 1264 * designed for use in monitoring system state, not for
1262 1265 * synchronization control.
1263 1266 *
1264 1267 * @return {@code true} if any thread holds the write lock and
1265 1268 * {@code false} otherwise
1266 1269 */
1267 1270 public boolean isWriteLocked() {
1268 1271 return sync.isWriteLocked();
1269 1272 }
1270 1273
1271 1274 /**
1272 1275 * Queries if the write lock is held by the current thread.
1273 1276 *
1274 1277 * @return {@code true} if the current thread holds the write lock and
1275 1278 * {@code false} otherwise
1276 1279 */
1277 1280 public boolean isWriteLockedByCurrentThread() {
1278 1281 return sync.isHeldExclusively();
1279 1282 }
1280 1283
1281 1284 /**
1282 1285 * Queries the number of reentrant write holds on this lock by the
1283 1286 * current thread. A writer thread has a hold on a lock for
1284 1287 * each lock action that is not matched by an unlock action.
1285 1288 *
1286 1289 * @return the number of holds on the write lock by the current thread,
1287 1290 * or zero if the write lock is not held by the current thread
1288 1291 */
1289 1292 public int getWriteHoldCount() {
1290 1293 return sync.getWriteHoldCount();
1291 1294 }
1292 1295
1293 1296 /**
1294 1297 * Queries the number of reentrant read holds on this lock by the
1295 1298 * current thread. A reader thread has a hold on a lock for
1296 1299 * each lock action that is not matched by an unlock action.
1297 1300 *
1298 1301 * @return the number of holds on the read lock by the current thread,
1299 1302 * or zero if the read lock is not held by the current thread
1300 1303 * @since 1.6
1301 1304 */
1302 1305 public int getReadHoldCount() {
1303 1306 return sync.getReadHoldCount();
1304 1307 }
1305 1308
1306 1309 /**
1307 1310 * Returns a collection containing threads that may be waiting to
1308 1311 * acquire the write lock. Because the actual set of threads may
1309 1312 * change dynamically while constructing this result, the returned
1310 1313 * collection is only a best-effort estimate. The elements of the
1311 1314 * returned collection are in no particular order. This method is
1312 1315 * designed to facilitate construction of subclasses that provide
1313 1316 * more extensive lock monitoring facilities.
1314 1317 *
1315 1318 * @return the collection of threads
1316 1319 */
1317 1320 protected Collection<Thread> getQueuedWriterThreads() {
1318 1321 return sync.getExclusiveQueuedThreads();
1319 1322 }
1320 1323
1321 1324 /**
1322 1325 * Returns a collection containing threads that may be waiting to
1323 1326 * acquire the read lock. Because the actual set of threads may
1324 1327 * change dynamically while constructing this result, the returned
1325 1328 * collection is only a best-effort estimate. The elements of the
1326 1329 * returned collection are in no particular order. This method is
1327 1330 * designed to facilitate construction of subclasses that provide
1328 1331 * more extensive lock monitoring facilities.
1329 1332 *
1330 1333 * @return the collection of threads
1331 1334 */
1332 1335 protected Collection<Thread> getQueuedReaderThreads() {
1333 1336 return sync.getSharedQueuedThreads();
1334 1337 }
1335 1338
1336 1339 /**
1337 1340 * Queries whether any threads are waiting to acquire the read or
1338 1341 * write lock. Note that because cancellations may occur at any
1339 1342 * time, a {@code true} return does not guarantee that any other
1340 1343 * thread will ever acquire a lock. This method is designed
1341 1344 * primarily for use in monitoring of the system state.
1342 1345 *
1343 1346 * @return {@code true} if there may be other threads waiting to
1344 1347 * acquire the lock
1345 1348 */
1346 1349 public final boolean hasQueuedThreads() {
1347 1350 return sync.hasQueuedThreads();
1348 1351 }
1349 1352
1350 1353 /**
1351 1354 * Queries whether the given thread is waiting to acquire either
1352 1355 * the read or write lock. Note that because cancellations may
1353 1356 * occur at any time, a {@code true} return does not guarantee
1354 1357 * that this thread will ever acquire a lock. This method is
1355 1358 * designed primarily for use in monitoring of the system state.
1356 1359 *
1357 1360 * @param thread the thread
1358 1361 * @return {@code true} if the given thread is queued waiting for this lock
1359 1362 * @throws NullPointerException if the thread is null
1360 1363 */
1361 1364 public final boolean hasQueuedThread(Thread thread) {
1362 1365 return sync.isQueued(thread);
1363 1366 }
1364 1367
1365 1368 /**
1366 1369 * Returns an estimate of the number of threads waiting to acquire
1367 1370 * either the read or write lock. The value is only an estimate
1368 1371 * because the number of threads may change dynamically while this
1369 1372 * method traverses internal data structures. This method is
1370 1373 * designed for use in monitoring of the system state, not for
1371 1374 * synchronization control.
1372 1375 *
1373 1376 * @return the estimated number of threads waiting for this lock
1374 1377 */
1375 1378 public final int getQueueLength() {
1376 1379 return sync.getQueueLength();
1377 1380 }
1378 1381
1379 1382 /**
1380 1383 * Returns a collection containing threads that may be waiting to
1381 1384 * acquire either the read or write lock. Because the actual set
1382 1385 * of threads may change dynamically while constructing this
1383 1386 * result, the returned collection is only a best-effort estimate.
1384 1387 * The elements of the returned collection are in no particular
1385 1388 * order. This method is designed to facilitate construction of
1386 1389 * subclasses that provide more extensive monitoring facilities.
1387 1390 *
1388 1391 * @return the collection of threads
1389 1392 */
1390 1393 protected Collection<Thread> getQueuedThreads() {
1391 1394 return sync.getQueuedThreads();
1392 1395 }
1393 1396
1394 1397 /**
1395 1398 * Queries whether any threads are waiting on the given condition
1396 1399 * associated with the write lock. Note that because timeouts and
1397 1400 * interrupts may occur at any time, a {@code true} return does
1398 1401 * not guarantee that a future {@code signal} will awaken any
1399 1402 * threads. This method is designed primarily for use in
1400 1403 * monitoring of the system state.
1401 1404 *
1402 1405 * @param condition the condition
1403 1406 * @return {@code true} if there are any waiting threads
1404 1407 * @throws IllegalMonitorStateException if this lock is not held
1405 1408 * @throws IllegalArgumentException if the given condition is
1406 1409 * not associated with this lock
1407 1410 * @throws NullPointerException if the condition is null
1408 1411 */
1409 1412 public boolean hasWaiters(Condition condition) {
1410 1413 if (condition == null)
1411 1414 throw new NullPointerException();
1412 1415 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
1413 1416 throw new IllegalArgumentException("not owner");
1414 1417 return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
1415 1418 }
1416 1419
1417 1420 /**
1418 1421 * Returns an estimate of the number of threads waiting on the
1419 1422 * given condition associated with the write lock. Note that because
1420 1423 * timeouts and interrupts may occur at any time, the estimate
1421 1424 * serves only as an upper bound on the actual number of waiters.
1422 1425 * This method is designed for use in monitoring of the system
1423 1426 * state, not for synchronization control.
1424 1427 *
1425 1428 * @param condition the condition
1426 1429 * @return the estimated number of waiting threads
1427 1430 * @throws IllegalMonitorStateException if this lock is not held
1428 1431 * @throws IllegalArgumentException if the given condition is
1429 1432 * not associated with this lock
1430 1433 * @throws NullPointerException if the condition is null
1431 1434 */
1432 1435 public int getWaitQueueLength(Condition condition) {
1433 1436 if (condition == null)
1434 1437 throw new NullPointerException();
1435 1438 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
1436 1439 throw new IllegalArgumentException("not owner");
1437 1440 return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
1438 1441 }
1439 1442
1440 1443 /**
1441 1444 * Returns a collection containing those threads that may be
1442 1445 * waiting on the given condition associated with the write lock.
1443 1446 * Because the actual set of threads may change dynamically while
1444 1447 * constructing this result, the returned collection is only a
1445 1448 * best-effort estimate. The elements of the returned collection
1446 1449 * are in no particular order. This method is designed to
1447 1450 * facilitate construction of subclasses that provide more
1448 1451 * extensive condition monitoring facilities.
1449 1452 *
1450 1453 * @param condition the condition
1451 1454 * @return the collection of threads
1452 1455 * @throws IllegalMonitorStateException if this lock is not held
1453 1456 * @throws IllegalArgumentException if the given condition is
1454 1457 * not associated with this lock
1455 1458 * @throws NullPointerException if the condition is null
1456 1459 */
1457 1460 protected Collection<Thread> getWaitingThreads(Condition condition) {
1458 1461 if (condition == null)
1459 1462 throw new NullPointerException();
1460 1463 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
1461 1464 throw new IllegalArgumentException("not owner");
1462 1465 return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
1463 1466 }
1464 1467
1465 1468 /**
1466 1469 * Returns a string identifying this lock, as well as its lock state.
1467 1470 * The state, in brackets, includes the String {@code "Write locks ="}
1468 1471 * followed by the number of reentrantly held write locks, and the
1469 1472 * String {@code "Read locks ="} followed by the number of held
1470 1473 * read locks.
1471 1474 *
1472 1475 * @return a string identifying this lock, as well as its lock state
1473 1476 */
1474 1477 public String toString() {
1475 1478 int c = sync.getCount();
1476 1479 int w = Sync.exclusiveCount(c);
1477 1480 int r = Sync.sharedCount(c);
1478 1481
1479 1482 return super.toString() +
1480 1483 "[Write locks = " + w + ", Read locks = " + r + "]";
1481 1484 }
1482 1485
1483 1486 }
↓ open down ↓ |
362 lines elided |
↑ open up ↑ |
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX