blob: c9280c851270c7b2a5d5603788376fed81c7b7e6 [file] [log] [blame]
J. Duke319a3b92007-12-01 00:00:00 +00001/*
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. Sun designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21 * CA 95054 USA or visit www.sun.com if you need additional information or
22 * have any 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/licenses/publicdomain
34 */
35
36package java.util.concurrent.locks;
37import java.util.concurrent.*;
38import java.util.concurrent.atomic.*;
39import 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 */
218public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializable {
219 private static final long serialVersionUID = -6992448646407690164L;
220 /** Inner class providing readlock */
221 private final ReentrantReadWriteLock.ReadLock readerLock;
222 /** Inner class providing writelock */
223 private final ReentrantReadWriteLock.WriteLock writerLock;
224 /** Performs all synchronization mechanics */
225 private final Sync sync;
226
227 /**
228 * Creates a new {@code ReentrantReadWriteLock} with
229 * default (nonfair) ordering properties.
230 */
231 public ReentrantReadWriteLock() {
232 this(false);
233 }
234
235 /**
236 * Creates a new {@code ReentrantReadWriteLock} with
237 * the given fairness policy.
238 *
239 * @param fair {@code true} if this lock should use a fair ordering policy
240 */
241 public ReentrantReadWriteLock(boolean fair) {
242 sync = (fair)? new FairSync() : new NonfairSync();
243 readerLock = new ReadLock(this);
244 writerLock = new WriteLock(this);
245 }
246
247 public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; }
248 public ReentrantReadWriteLock.ReadLock readLock() { return readerLock; }
249
250 /**
251 * Synchronization implementation for ReentrantReadWriteLock.
252 * Subclassed into fair and nonfair versions.
253 */
254 static abstract class Sync extends AbstractQueuedSynchronizer {
255 private static final long serialVersionUID = 6317671515068378041L;
256
257 /*
258 * Read vs write count extraction constants and functions.
259 * Lock state is logically divided into two shorts: The lower
260 * one representing the exclusive (writer) lock hold count,
261 * and the upper the shared (reader) hold count.
262 */
263
264 static final int SHARED_SHIFT = 16;
265 static final int SHARED_UNIT = (1 << SHARED_SHIFT);
266 static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1;
267 static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
268
269 /** Returns the number of shared holds represented in count */
270 static int sharedCount(int c) { return c >>> SHARED_SHIFT; }
271 /** Returns the number of exclusive holds represented in count */
272 static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
273
274 /**
275 * A counter for per-thread read hold counts.
276 * Maintained as a ThreadLocal; cached in cachedHoldCounter
277 */
278 static final class HoldCounter {
279 int count;
280 // Use id, not reference, to avoid garbage retention
281 final long tid = Thread.currentThread().getId();
282 /** Decrement if positive; return previous value */
283 int tryDecrement() {
284 int c = count;
285 if (c > 0)
286 count = c - 1;
287 return c;
288 }
289 }
290
291 /**
292 * ThreadLocal subclass. Easiest to explicitly define for sake
293 * of deserialization mechanics.
294 */
295 static final class ThreadLocalHoldCounter
296 extends ThreadLocal<HoldCounter> {
297 public HoldCounter initialValue() {
298 return new HoldCounter();
299 }
300 }
301
302 /**
303 * The number of read locks held by current thread.
304 * Initialized only in constructor and readObject.
305 */
306 transient ThreadLocalHoldCounter readHolds;
307
308 /**
309 * The hold count of the last thread to successfully acquire
310 * readLock. This saves ThreadLocal lookup in the common case
311 * where the next thread to release is the last one to
312 * acquire. This is non-volatile since it is just used
313 * as a heuristic, and would be great for threads to cache.
314 */
315 transient HoldCounter cachedHoldCounter;
316
317 Sync() {
318 readHolds = new ThreadLocalHoldCounter();
319 setState(getState()); // ensures visibility of readHolds
320 }
321
322 /*
323 * Acquires and releases use the same code for fair and
324 * nonfair locks, but differ in whether/how they allow barging
325 * when queues are non-empty.
326 */
327
328 /**
329 * Returns true if the current thread, when trying to acquire
330 * the read lock, and otherwise eligible to do so, should block
331 * because of policy for overtaking other waiting threads.
332 */
333 abstract boolean readerShouldBlock();
334
335 /**
336 * Returns true if the current thread, when trying to acquire
337 * the write lock, and otherwise eligible to do so, should block
338 * because of policy for overtaking other waiting threads.
339 */
340 abstract boolean writerShouldBlock();
341
342 /*
343 * Note that tryRelease and tryAcquire can be called by
344 * Conditions. So it is possible that their arguments contain
345 * both read and write holds that are all released during a
346 * condition wait and re-established in tryAcquire.
347 */
348
349 protected final boolean tryRelease(int releases) {
350 if (!isHeldExclusively())
351 throw new IllegalMonitorStateException();
352 int nextc = getState() - releases;
353 boolean free = exclusiveCount(nextc) == 0;
354 if (free)
355 setExclusiveOwnerThread(null);
356 setState(nextc);
357 return free;
358 }
359
360 protected final boolean tryAcquire(int acquires) {
361 /*
362 * Walkthrough:
363 * 1. If read count nonzero or write count nonzero
364 * and owner is a different thread, fail.
365 * 2. If count would saturate, fail. (This can only
366 * happen if count is already nonzero.)
367 * 3. Otherwise, this thread is eligible for lock if
368 * it is either a reentrant acquire or
369 * queue policy allows it. If so, update state
370 * and set owner.
371 */
372 Thread current = Thread.currentThread();
373 int c = getState();
374 int w = exclusiveCount(c);
375 if (c != 0) {
376 // (Note: if c != 0 and w == 0 then shared count != 0)
377 if (w == 0 || current != getExclusiveOwnerThread())
378 return false;
379 if (w + exclusiveCount(acquires) > MAX_COUNT)
380 throw new Error("Maximum lock count exceeded");
381 // Reentrant acquire
382 setState(c + acquires);
383 return true;
384 }
385 if (writerShouldBlock() ||
386 !compareAndSetState(c, c + acquires))
387 return false;
388 setExclusiveOwnerThread(current);
389 return true;
390 }
391
392 protected final boolean tryReleaseShared(int unused) {
393 HoldCounter rh = cachedHoldCounter;
394 Thread current = Thread.currentThread();
395 if (rh == null || rh.tid != current.getId())
396 rh = readHolds.get();
397 if (rh.tryDecrement() <= 0)
398 throw new IllegalMonitorStateException();
399 for (;;) {
400 int c = getState();
401 int nextc = c - SHARED_UNIT;
402 if (compareAndSetState(c, nextc))
403 return nextc == 0;
404 }
405 }
406
407 protected final int tryAcquireShared(int unused) {
408 /*
409 * Walkthrough:
410 * 1. If write lock held by another thread, fail.
411 * 2. If count saturated, throw error.
412 * 3. Otherwise, this thread is eligible for
413 * lock wrt state, so ask if it should block
414 * because of queue policy. If not, try
415 * to grant by CASing state and updating count.
416 * Note that step does not check for reentrant
417 * acquires, which is postponed to full version
418 * to avoid having to check hold count in
419 * the more typical non-reentrant case.
420 * 4. If step 3 fails either because thread
421 * apparently not eligible or CAS fails,
422 * chain to version with full retry loop.
423 */
424 Thread current = Thread.currentThread();
425 int c = getState();
426 if (exclusiveCount(c) != 0 &&
427 getExclusiveOwnerThread() != current)
428 return -1;
429 if (sharedCount(c) == MAX_COUNT)
430 throw new Error("Maximum lock count exceeded");
431 if (!readerShouldBlock() &&
432 compareAndSetState(c, c + SHARED_UNIT)) {
433 HoldCounter rh = cachedHoldCounter;
434 if (rh == null || rh.tid != current.getId())
435 cachedHoldCounter = rh = readHolds.get();
436 rh.count++;
437 return 1;
438 }
439 return fullTryAcquireShared(current);
440 }
441
442 /**
443 * Full version of acquire for reads, that handles CAS misses
444 * and reentrant reads not dealt with in tryAcquireShared.
445 */
446 final int fullTryAcquireShared(Thread current) {
447 /*
448 * This code is in part redundant with that in
449 * tryAcquireShared but is simpler overall by not
450 * complicating tryAcquireShared with interactions between
451 * retries and lazily reading hold counts.
452 */
453 HoldCounter rh = cachedHoldCounter;
454 if (rh == null || rh.tid != current.getId())
455 rh = readHolds.get();
456 for (;;) {
457 int c = getState();
458 int w = exclusiveCount(c);
459 if ((w != 0 && getExclusiveOwnerThread() != current) ||
460 ((rh.count | w) == 0 && readerShouldBlock()))
461 return -1;
462 if (sharedCount(c) == MAX_COUNT)
463 throw new Error("Maximum lock count exceeded");
464 if (compareAndSetState(c, c + SHARED_UNIT)) {
465 cachedHoldCounter = rh; // cache for release
466 rh.count++;
467 return 1;
468 }
469 }
470 }
471
472 /**
473 * Performs tryLock for write, enabling barging in both modes.
474 * This is identical in effect to tryAcquire except for lack
475 * of calls to writerShouldBlock
476 */
477 final boolean tryWriteLock() {
478 Thread current = Thread.currentThread();
479 int c = getState();
480 if (c != 0) {
481 int w = exclusiveCount(c);
482 if (w == 0 ||current != getExclusiveOwnerThread())
483 return false;
484 if (w == MAX_COUNT)
485 throw new Error("Maximum lock count exceeded");
486 }
487 if (!compareAndSetState(c, c + 1))
488 return false;
489 setExclusiveOwnerThread(current);
490 return true;
491 }
492
493 /**
494 * Performs tryLock for read, enabling barging in both modes.
495 * This is identical in effect to tryAcquireShared except for
496 * lack of calls to readerShouldBlock
497 */
498 final boolean tryReadLock() {
499 Thread current = Thread.currentThread();
500 for (;;) {
501 int c = getState();
502 if (exclusiveCount(c) != 0 &&
503 getExclusiveOwnerThread() != current)
504 return false;
505 if (sharedCount(c) == MAX_COUNT)
506 throw new Error("Maximum lock count exceeded");
507 if (compareAndSetState(c, c + SHARED_UNIT)) {
508 HoldCounter rh = cachedHoldCounter;
509 if (rh == null || rh.tid != current.getId())
510 cachedHoldCounter = rh = readHolds.get();
511 rh.count++;
512 return true;
513 }
514 }
515 }
516
517 protected final boolean isHeldExclusively() {
518 // While we must in general read state before owner,
519 // we don't need to do so to check if current thread is owner
520 return getExclusiveOwnerThread() == Thread.currentThread();
521 }
522
523 // Methods relayed to outer class
524
525 final ConditionObject newCondition() {
526 return new ConditionObject();
527 }
528
529 final Thread getOwner() {
530 // Must read state before owner to ensure memory consistency
531 return ((exclusiveCount(getState()) == 0)?
532 null :
533 getExclusiveOwnerThread());
534 }
535
536 final int getReadLockCount() {
537 return sharedCount(getState());
538 }
539
540 final boolean isWriteLocked() {
541 return exclusiveCount(getState()) != 0;
542 }
543
544 final int getWriteHoldCount() {
545 return isHeldExclusively() ? exclusiveCount(getState()) : 0;
546 }
547
548 final int getReadHoldCount() {
549 return getReadLockCount() == 0? 0 : readHolds.get().count;
550 }
551
552 /**
553 * Reconstitute this lock instance from a stream
554 * @param s the stream
555 */
556 private void readObject(java.io.ObjectInputStream s)
557 throws java.io.IOException, ClassNotFoundException {
558 s.defaultReadObject();
559 readHolds = new ThreadLocalHoldCounter();
560 setState(0); // reset to unlocked state
561 }
562
563 final int getCount() { return getState(); }
564 }
565
566 /**
567 * Nonfair version of Sync
568 */
569 final static class NonfairSync extends Sync {
570 private static final long serialVersionUID = -8159625535654395037L;
571 final boolean writerShouldBlock() {
572 return false; // writers can always barge
573 }
574 final boolean readerShouldBlock() {
575 /* As a heuristic to avoid indefinite writer starvation,
576 * block if the thread that momentarily appears to be head
577 * of queue, if one exists, is a waiting writer. This is
578 * only a probabilistic effect since a new reader will not
579 * block if there is a waiting writer behind other enabled
580 * readers that have not yet drained from the queue.
581 */
582 return apparentlyFirstQueuedIsExclusive();
583 }
584 }
585
586 /**
587 * Fair version of Sync
588 */
589 final static class FairSync extends Sync {
590 private static final long serialVersionUID = -2274990926593161451L;
591 final boolean writerShouldBlock() {
592 return hasQueuedPredecessors();
593 }
594 final boolean readerShouldBlock() {
595 return hasQueuedPredecessors();
596 }
597 }
598
599 /**
600 * The lock returned by method {@link ReentrantReadWriteLock#readLock}.
601 */
602 public static class ReadLock implements Lock, java.io.Serializable {
603 private static final long serialVersionUID = -5992448646407690164L;
604 private final Sync sync;
605
606 /**
607 * Constructor for use by subclasses
608 *
609 * @param lock the outer lock object
610 * @throws NullPointerException if the lock is null
611 */
612 protected ReadLock(ReentrantReadWriteLock lock) {
613 sync = lock.sync;
614 }
615
616 /**
617 * Acquires the read lock.
618 *
619 * <p>Acquires the read lock if the write lock is not held by
620 * another thread and returns immediately.
621 *
622 * <p>If the write lock is held by another thread then
623 * the current thread becomes disabled for thread scheduling
624 * purposes and lies dormant until the read lock has been acquired.
625 */
626 public void lock() {
627 sync.acquireShared(1);
628 }
629
630 /**
631 * Acquires the read lock unless the current thread is
632 * {@linkplain Thread#interrupt interrupted}.
633 *
634 * <p>Acquires the read lock if the write lock is not held
635 * by another thread and returns immediately.
636 *
637 * <p>If the write lock is held by another thread then the
638 * current thread becomes disabled for thread scheduling
639 * purposes and lies dormant until one of two things happens:
640 *
641 * <ul>
642 *
643 * <li>The read lock is acquired by the current thread; or
644 *
645 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
646 * the current thread.
647 *
648 * </ul>
649 *
650 * <p>If the current thread:
651 *
652 * <ul>
653 *
654 * <li>has its interrupted status set on entry to this method; or
655 *
656 * <li>is {@linkplain Thread#interrupt interrupted} while
657 * acquiring the read lock,
658 *
659 * </ul>
660 *
661 * then {@link InterruptedException} is thrown and the current
662 * thread's interrupted status is cleared.
663 *
664 * <p>In this implementation, as this method is an explicit
665 * interruption point, preference is given to responding to
666 * the interrupt over normal or reentrant acquisition of the
667 * lock.
668 *
669 * @throws InterruptedException if the current thread is interrupted
670 */
671 public void lockInterruptibly() throws InterruptedException {
672 sync.acquireSharedInterruptibly(1);
673 }
674
675 /**
676 * Acquires the read lock only if the write lock is not held by
677 * another thread at the time of invocation.
678 *
679 * <p>Acquires the read lock if the write lock is not held by
680 * another thread and returns immediately with the value
681 * {@code true}. Even when this lock has been set to use a
682 * fair ordering policy, a call to {@code tryLock()}
683 * <em>will</em> immediately acquire the read lock if it is
684 * available, whether or not other threads are currently
685 * waiting for the read lock. This &quot;barging&quot; behavior
686 * can be useful in certain circumstances, even though it
687 * breaks fairness. If you want to honor the fairness setting
688 * for this lock, then use {@link #tryLock(long, TimeUnit)
689 * tryLock(0, TimeUnit.SECONDS) } which is almost equivalent
690 * (it also detects interruption).
691 *
692 * <p>If the write lock is held by another thread then
693 * this method will return immediately with the value
694 * {@code false}.
695 *
696 * @return {@code true} if the read lock was acquired
697 */
698 public boolean tryLock() {
699 return sync.tryReadLock();
700 }
701
702 /**
703 * Acquires the read lock if the write lock is not held by
704 * another thread within the given waiting time and the
705 * current thread has not been {@linkplain Thread#interrupt
706 * interrupted}.
707 *
708 * <p>Acquires the read lock if the write lock is not held by
709 * another thread and returns immediately with the value
710 * {@code true}. If this lock has been set to use a fair
711 * ordering policy then an available lock <em>will not</em> be
712 * acquired if any other threads are waiting for the
713 * lock. This is in contrast to the {@link #tryLock()}
714 * method. If you want a timed {@code tryLock} that does
715 * permit barging on a fair lock then combine the timed and
716 * un-timed forms together:
717 *
718 * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
719 * </pre>
720 *
721 * <p>If the write lock is held by another thread then the
722 * current thread becomes disabled for thread scheduling
723 * purposes and lies dormant until one of three things happens:
724 *
725 * <ul>
726 *
727 * <li>The read lock is acquired by the current thread; or
728 *
729 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
730 * the current thread; or
731 *
732 * <li>The specified waiting time elapses.
733 *
734 * </ul>
735 *
736 * <p>If the read lock is acquired then the value {@code true} is
737 * returned.
738 *
739 * <p>If the current thread:
740 *
741 * <ul>
742 *
743 * <li>has its interrupted status set on entry to this method; or
744 *
745 * <li>is {@linkplain Thread#interrupt interrupted} while
746 * acquiring the read lock,
747 *
748 * </ul> then {@link InterruptedException} is thrown and the
749 * current thread's interrupted status is cleared.
750 *
751 * <p>If the specified waiting time elapses then the value
752 * {@code false} is returned. If the time is less than or
753 * equal to zero, the method will not wait at all.
754 *
755 * <p>In this implementation, as this method is an explicit
756 * interruption point, preference is given to responding to
757 * the interrupt over normal or reentrant acquisition of the
758 * lock, and over reporting the elapse of the waiting time.
759 *
760 * @param timeout the time to wait for the read lock
761 * @param unit the time unit of the timeout argument
762 * @return {@code true} if the read lock was acquired
763 * @throws InterruptedException if the current thread is interrupted
764 * @throws NullPointerException if the time unit is null
765 *
766 */
767 public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
768 return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
769 }
770
771 /**
772 * Attempts to release this lock.
773 *
774 * <p> If the number of readers is now zero then the lock
775 * is made available for write lock attempts.
776 */
777 public void unlock() {
778 sync.releaseShared(1);
779 }
780
781 /**
782 * Throws {@code UnsupportedOperationException} because
783 * {@code ReadLocks} do not support conditions.
784 *
785 * @throws UnsupportedOperationException always
786 */
787 public Condition newCondition() {
788 throw new UnsupportedOperationException();
789 }
790
791 /**
792 * Returns a string identifying this lock, as well as its lock state.
793 * The state, in brackets, includes the String {@code "Read locks ="}
794 * followed by the number of held read locks.
795 *
796 * @return a string identifying this lock, as well as its lock state
797 */
798 public String toString() {
799 int r = sync.getReadLockCount();
800 return super.toString() +
801 "[Read locks = " + r + "]";
802 }
803 }
804
805 /**
806 * The lock returned by method {@link ReentrantReadWriteLock#writeLock}.
807 */
808 public static class WriteLock implements Lock, java.io.Serializable {
809 private static final long serialVersionUID = -4992448646407690164L;
810 private final Sync sync;
811
812 /**
813 * Constructor for use by subclasses
814 *
815 * @param lock the outer lock object
816 * @throws NullPointerException if the lock is null
817 */
818 protected WriteLock(ReentrantReadWriteLock lock) {
819 sync = lock.sync;
820 }
821
822 /**
823 * Acquires the write lock.
824 *
825 * <p>Acquires the write lock if neither the read nor write lock
826 * are held by another thread
827 * and returns immediately, setting the write lock hold count to
828 * one.
829 *
830 * <p>If the current thread already holds the write lock then the
831 * hold count is incremented by one and the method returns
832 * immediately.
833 *
834 * <p>If the lock is held by another thread then the current
835 * thread becomes disabled for thread scheduling purposes and
836 * lies dormant until the write lock has been acquired, at which
837 * time the write lock hold count is set to one.
838 */
839 public void lock() {
840 sync.acquire(1);
841 }
842
843 /**
844 * Acquires the write lock unless the current thread is
845 * {@linkplain Thread#interrupt interrupted}.
846 *
847 * <p>Acquires the write lock if neither the read nor write lock
848 * are held by another thread
849 * and returns immediately, setting the write lock hold count to
850 * one.
851 *
852 * <p>If the current thread already holds this lock then the
853 * hold count is incremented by one and the method returns
854 * immediately.
855 *
856 * <p>If the lock is held by another thread then the current
857 * thread becomes disabled for thread scheduling purposes and
858 * lies dormant until one of two things happens:
859 *
860 * <ul>
861 *
862 * <li>The write lock is acquired by the current thread; or
863 *
864 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
865 * the current thread.
866 *
867 * </ul>
868 *
869 * <p>If the write lock is acquired by the current thread then the
870 * lock hold count is set to one.
871 *
872 * <p>If the current thread:
873 *
874 * <ul>
875 *
876 * <li>has its interrupted status set on entry to this method;
877 * or
878 *
879 * <li>is {@linkplain Thread#interrupt interrupted} while
880 * acquiring the write lock,
881 *
882 * </ul>
883 *
884 * then {@link InterruptedException} is thrown and the current
885 * thread's interrupted status is cleared.
886 *
887 * <p>In this implementation, as this method is an explicit
888 * interruption point, preference is given to responding to
889 * the interrupt over normal or reentrant acquisition of the
890 * lock.
891 *
892 * @throws InterruptedException if the current thread is interrupted
893 */
894 public void lockInterruptibly() throws InterruptedException {
895 sync.acquireInterruptibly(1);
896 }
897
898 /**
899 * Acquires the write lock only if it is not held by another thread
900 * at the time of invocation.
901 *
902 * <p>Acquires the write lock if neither the read nor write lock
903 * are held by another thread
904 * and returns immediately with the value {@code true},
905 * setting the write lock hold count to one. Even when this lock has
906 * been set to use a fair ordering policy, a call to
907 * {@code tryLock()} <em>will</em> immediately acquire the
908 * lock if it is available, whether or not other threads are
909 * currently waiting for the write lock. This &quot;barging&quot;
910 * behavior can be useful in certain circumstances, even
911 * though it breaks fairness. If you want to honor the
912 * fairness setting for this lock, then use {@link
913 * #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
914 * which is almost equivalent (it also detects interruption).
915 *
916 * <p> If the current thread already holds this lock then the
917 * hold count is incremented by one and the method returns
918 * {@code true}.
919 *
920 * <p>If the lock is held by another thread then this method
921 * will return immediately with the value {@code false}.
922 *
923 * @return {@code true} if the lock was free and was acquired
924 * by the current thread, or the write lock was already held
925 * by the current thread; and {@code false} otherwise.
926 */
927 public boolean tryLock( ) {
928 return sync.tryWriteLock();
929 }
930
931 /**
932 * Acquires the write lock if it is not held by another thread
933 * within the given waiting time and the current thread has
934 * not been {@linkplain Thread#interrupt interrupted}.
935 *
936 * <p>Acquires the write lock if neither the read nor write lock
937 * are held by another thread
938 * and returns immediately with the value {@code true},
939 * setting the write lock hold count to one. If this lock has been
940 * set to use a fair ordering policy then an available lock
941 * <em>will not</em> be acquired if any other threads are
942 * waiting for the write lock. This is in contrast to the {@link
943 * #tryLock()} method. If you want a timed {@code tryLock}
944 * that does permit barging on a fair lock then combine the
945 * timed and un-timed forms together:
946 *
947 * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
948 * </pre>
949 *
950 * <p>If the current thread already holds this lock then the
951 * hold count is incremented by one and the method returns
952 * {@code true}.
953 *
954 * <p>If the lock is held by another thread then the current
955 * thread becomes disabled for thread scheduling purposes and
956 * lies dormant until one of three things happens:
957 *
958 * <ul>
959 *
960 * <li>The write lock is acquired by the current thread; or
961 *
962 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
963 * the current thread; or
964 *
965 * <li>The specified waiting time elapses
966 *
967 * </ul>
968 *
969 * <p>If the write lock is acquired then the value {@code true} is
970 * returned and the write lock hold count is set to one.
971 *
972 * <p>If the current thread:
973 *
974 * <ul>
975 *
976 * <li>has its interrupted status set on entry to this method;
977 * or
978 *
979 * <li>is {@linkplain Thread#interrupt interrupted} while
980 * acquiring the write lock,
981 *
982 * </ul>
983 *
984 * then {@link InterruptedException} is thrown and the current
985 * thread's interrupted status is cleared.
986 *
987 * <p>If the specified waiting time elapses then the value
988 * {@code false} is returned. If the time is less than or
989 * equal to zero, the method will not wait at all.
990 *
991 * <p>In this implementation, as this method is an explicit
992 * interruption point, preference is given to responding to
993 * the interrupt over normal or reentrant acquisition of the
994 * lock, and over reporting the elapse of the waiting time.
995 *
996 * @param timeout the time to wait for the write lock
997 * @param unit the time unit of the timeout argument
998 *
999 * @return {@code true} if the lock was free and was acquired
1000 * by the current thread, or the write lock was already held by the
1001 * current thread; and {@code false} if the waiting time
1002 * elapsed before the lock could be acquired.
1003 *
1004 * @throws InterruptedException if the current thread is interrupted
1005 * @throws NullPointerException if the time unit is null
1006 *
1007 */
1008 public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
1009 return sync.tryAcquireNanos(1, unit.toNanos(timeout));
1010 }
1011
1012 /**
1013 * Attempts to release this lock.
1014 *
1015 * <p>If the current thread is the holder of this lock then
1016 * the hold count is decremented. If the hold count is now
1017 * zero then the lock is released. If the current thread is
1018 * not the holder of this lock then {@link
1019 * IllegalMonitorStateException} is thrown.
1020 *
1021 * @throws IllegalMonitorStateException if the current thread does not
1022 * hold this lock.
1023 */
1024 public void unlock() {
1025 sync.release(1);
1026 }
1027
1028 /**
1029 * Returns a {@link Condition} instance for use with this
1030 * {@link Lock} instance.
1031 * <p>The returned {@link Condition} instance supports the same
1032 * usages as do the {@link Object} monitor methods ({@link
1033 * Object#wait() wait}, {@link Object#notify notify}, and {@link
1034 * Object#notifyAll notifyAll}) when used with the built-in
1035 * monitor lock.
1036 *
1037 * <ul>
1038 *
1039 * <li>If this write lock is not held when any {@link
1040 * Condition} method is called then an {@link
1041 * IllegalMonitorStateException} is thrown. (Read locks are
1042 * held independently of write locks, so are not checked or
1043 * affected. However it is essentially always an error to
1044 * invoke a condition waiting method when the current thread
1045 * has also acquired read locks, since other threads that
1046 * could unblock it will not be able to acquire the write
1047 * lock.)
1048 *
1049 * <li>When the condition {@linkplain Condition#await() waiting}
1050 * methods are called the write lock is released and, before
1051 * they return, the write lock is reacquired and the lock hold
1052 * count restored to what it was when the method was called.
1053 *
1054 * <li>If a thread is {@linkplain Thread#interrupt interrupted} while
1055 * waiting then the wait will terminate, an {@link
1056 * InterruptedException} will be thrown, and the thread's
1057 * interrupted status will be cleared.
1058 *
1059 * <li> Waiting threads are signalled in FIFO order.
1060 *
1061 * <li>The ordering of lock reacquisition for threads returning
1062 * from waiting methods is the same as for threads initially
1063 * acquiring the lock, which is in the default case not specified,
1064 * but for <em>fair</em> locks favors those threads that have been
1065 * waiting the longest.
1066 *
1067 * </ul>
1068 *
1069 * @return the Condition object
1070 */
1071 public Condition newCondition() {
1072 return sync.newCondition();
1073 }
1074
1075 /**
1076 * Returns a string identifying this lock, as well as its lock
1077 * state. The state, in brackets includes either the String
1078 * {@code "Unlocked"} or the String {@code "Locked by"}
1079 * followed by the {@linkplain Thread#getName name} of the owning thread.
1080 *
1081 * @return a string identifying this lock, as well as its lock state
1082 */
1083 public String toString() {
1084 Thread o = sync.getOwner();
1085 return super.toString() + ((o == null) ?
1086 "[Unlocked]" :
1087 "[Locked by thread " + o.getName() + "]");
1088 }
1089
1090 /**
1091 * Queries if this write lock is held by the current thread.
1092 * Identical in effect to {@link
1093 * ReentrantReadWriteLock#isWriteLockedByCurrentThread}.
1094 *
1095 * @return {@code true} if the current thread holds this lock and
1096 * {@code false} otherwise
1097 * @since 1.6
1098 */
1099 public boolean isHeldByCurrentThread() {
1100 return sync.isHeldExclusively();
1101 }
1102
1103 /**
1104 * Queries the number of holds on this write lock by the current
1105 * thread. A thread has a hold on a lock for each lock action
1106 * that is not matched by an unlock action. Identical in effect
1107 * to {@link ReentrantReadWriteLock#getWriteHoldCount}.
1108 *
1109 * @return the number of holds on this lock by the current thread,
1110 * or zero if this lock is not held by the current thread
1111 * @since 1.6
1112 */
1113 public int getHoldCount() {
1114 return sync.getWriteHoldCount();
1115 }
1116 }
1117
1118 // Instrumentation and status
1119
1120 /**
1121 * Returns {@code true} if this lock has fairness set true.
1122 *
1123 * @return {@code true} if this lock has fairness set true
1124 */
1125 public final boolean isFair() {
1126 return sync instanceof FairSync;
1127 }
1128
1129 /**
1130 * Returns the thread that currently owns the write lock, or
1131 * {@code null} if not owned. When this method is called by a
1132 * thread that is not the owner, the return value reflects a
1133 * best-effort approximation of current lock status. For example,
1134 * the owner may be momentarily {@code null} even if there are
1135 * threads trying to acquire the lock but have not yet done so.
1136 * This method is designed to facilitate construction of
1137 * subclasses that provide more extensive lock monitoring
1138 * facilities.
1139 *
1140 * @return the owner, or {@code null} if not owned
1141 */
1142 protected Thread getOwner() {
1143 return sync.getOwner();
1144 }
1145
1146 /**
1147 * Queries the number of read locks held for this lock. This
1148 * method is designed for use in monitoring system state, not for
1149 * synchronization control.
1150 * @return the number of read locks held.
1151 */
1152 public int getReadLockCount() {
1153 return sync.getReadLockCount();
1154 }
1155
1156 /**
1157 * Queries if the write lock is held by any thread. This method is
1158 * designed for use in monitoring system state, not for
1159 * synchronization control.
1160 *
1161 * @return {@code true} if any thread holds the write lock and
1162 * {@code false} otherwise
1163 */
1164 public boolean isWriteLocked() {
1165 return sync.isWriteLocked();
1166 }
1167
1168 /**
1169 * Queries if the write lock is held by the current thread.
1170 *
1171 * @return {@code true} if the current thread holds the write lock and
1172 * {@code false} otherwise
1173 */
1174 public boolean isWriteLockedByCurrentThread() {
1175 return sync.isHeldExclusively();
1176 }
1177
1178 /**
1179 * Queries the number of reentrant write holds on this lock by the
1180 * current thread. A writer thread has a hold on a lock for
1181 * each lock action that is not matched by an unlock action.
1182 *
1183 * @return the number of holds on the write lock by the current thread,
1184 * or zero if the write lock is not held by the current thread
1185 */
1186 public int getWriteHoldCount() {
1187 return sync.getWriteHoldCount();
1188 }
1189
1190 /**
1191 * Queries the number of reentrant read holds on this lock by the
1192 * current thread. A reader thread has a hold on a lock for
1193 * each lock action that is not matched by an unlock action.
1194 *
1195 * @return the number of holds on the read lock by the current thread,
1196 * or zero if the read lock is not held by the current thread
1197 * @since 1.6
1198 */
1199 public int getReadHoldCount() {
1200 return sync.getReadHoldCount();
1201 }
1202
1203 /**
1204 * Returns a collection containing threads that may be waiting to
1205 * acquire the write lock. Because the actual set of threads may
1206 * change dynamically while constructing this result, the returned
1207 * collection is only a best-effort estimate. The elements of the
1208 * returned collection are in no particular order. This method is
1209 * designed to facilitate construction of subclasses that provide
1210 * more extensive lock monitoring facilities.
1211 *
1212 * @return the collection of threads
1213 */
1214 protected Collection<Thread> getQueuedWriterThreads() {
1215 return sync.getExclusiveQueuedThreads();
1216 }
1217
1218 /**
1219 * Returns a collection containing threads that may be waiting to
1220 * acquire the read lock. Because the actual set of threads may
1221 * change dynamically while constructing this result, the returned
1222 * collection is only a best-effort estimate. The elements of the
1223 * returned collection are in no particular order. This method is
1224 * designed to facilitate construction of subclasses that provide
1225 * more extensive lock monitoring facilities.
1226 *
1227 * @return the collection of threads
1228 */
1229 protected Collection<Thread> getQueuedReaderThreads() {
1230 return sync.getSharedQueuedThreads();
1231 }
1232
1233 /**
1234 * Queries whether any threads are waiting to acquire the read or
1235 * write lock. Note that because cancellations may occur at any
1236 * time, a {@code true} return does not guarantee that any other
1237 * thread will ever acquire a lock. This method is designed
1238 * primarily for use in monitoring of the system state.
1239 *
1240 * @return {@code true} if there may be other threads waiting to
1241 * acquire the lock
1242 */
1243 public final boolean hasQueuedThreads() {
1244 return sync.hasQueuedThreads();
1245 }
1246
1247 /**
1248 * Queries whether the given thread is waiting to acquire either
1249 * the read or write lock. Note that because cancellations may
1250 * occur at any time, a {@code true} return does not guarantee
1251 * that this thread will ever acquire a lock. This method is
1252 * designed primarily for use in monitoring of the system state.
1253 *
1254 * @param thread the thread
1255 * @return {@code true} if the given thread is queued waiting for this lock
1256 * @throws NullPointerException if the thread is null
1257 */
1258 public final boolean hasQueuedThread(Thread thread) {
1259 return sync.isQueued(thread);
1260 }
1261
1262 /**
1263 * Returns an estimate of the number of threads waiting to acquire
1264 * either the read or write lock. The value is only an estimate
1265 * because the number of threads may change dynamically while this
1266 * method traverses internal data structures. This method is
1267 * designed for use in monitoring of the system state, not for
1268 * synchronization control.
1269 *
1270 * @return the estimated number of threads waiting for this lock
1271 */
1272 public final int getQueueLength() {
1273 return sync.getQueueLength();
1274 }
1275
1276 /**
1277 * Returns a collection containing threads that may be waiting to
1278 * acquire either the read or write lock. Because the actual set
1279 * of threads may change dynamically while constructing this
1280 * result, the returned collection is only a best-effort estimate.
1281 * The elements of the returned collection are in no particular
1282 * order. This method is designed to facilitate construction of
1283 * subclasses that provide more extensive monitoring facilities.
1284 *
1285 * @return the collection of threads
1286 */
1287 protected Collection<Thread> getQueuedThreads() {
1288 return sync.getQueuedThreads();
1289 }
1290
1291 /**
1292 * Queries whether any threads are waiting on the given condition
1293 * associated with the write lock. Note that because timeouts and
1294 * interrupts may occur at any time, a {@code true} return does
1295 * not guarantee that a future {@code signal} will awaken any
1296 * threads. This method is designed primarily for use in
1297 * monitoring of the system state.
1298 *
1299 * @param condition the condition
1300 * @return {@code true} if there are any waiting threads
1301 * @throws IllegalMonitorStateException if this lock is not held
1302 * @throws IllegalArgumentException if the given condition is
1303 * not associated with this lock
1304 * @throws NullPointerException if the condition is null
1305 */
1306 public boolean hasWaiters(Condition condition) {
1307 if (condition == null)
1308 throw new NullPointerException();
1309 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
1310 throw new IllegalArgumentException("not owner");
1311 return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
1312 }
1313
1314 /**
1315 * Returns an estimate of the number of threads waiting on the
1316 * given condition associated with the write lock. Note that because
1317 * timeouts and interrupts may occur at any time, the estimate
1318 * serves only as an upper bound on the actual number of waiters.
1319 * This method is designed for use in monitoring of the system
1320 * state, not for synchronization control.
1321 *
1322 * @param condition the condition
1323 * @return the estimated number of waiting threads
1324 * @throws IllegalMonitorStateException if this lock is not held
1325 * @throws IllegalArgumentException if the given condition is
1326 * not associated with this lock
1327 * @throws NullPointerException if the condition is null
1328 */
1329 public int getWaitQueueLength(Condition condition) {
1330 if (condition == null)
1331 throw new NullPointerException();
1332 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
1333 throw new IllegalArgumentException("not owner");
1334 return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
1335 }
1336
1337 /**
1338 * Returns a collection containing those threads that may be
1339 * waiting on the given condition associated with the write lock.
1340 * Because the actual set of threads may change dynamically while
1341 * constructing this result, the returned collection is only a
1342 * best-effort estimate. The elements of the returned collection
1343 * are in no particular order. This method is designed to
1344 * facilitate construction of subclasses that provide more
1345 * extensive condition monitoring facilities.
1346 *
1347 * @param condition the condition
1348 * @return the collection of threads
1349 * @throws IllegalMonitorStateException if this lock is not held
1350 * @throws IllegalArgumentException if the given condition is
1351 * not associated with this lock
1352 * @throws NullPointerException if the condition is null
1353 */
1354 protected Collection<Thread> getWaitingThreads(Condition condition) {
1355 if (condition == null)
1356 throw new NullPointerException();
1357 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
1358 throw new IllegalArgumentException("not owner");
1359 return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
1360 }
1361
1362 /**
1363 * Returns a string identifying this lock, as well as its lock state.
1364 * The state, in brackets, includes the String {@code "Write locks ="}
1365 * followed by the number of reentrantly held write locks, and the
1366 * String {@code "Read locks ="} followed by the number of held
1367 * read locks.
1368 *
1369 * @return a string identifying this lock, as well as its lock state
1370 */
1371 public String toString() {
1372 int c = sync.getCount();
1373 int w = Sync.exclusiveCount(c);
1374 int r = Sync.sharedCount(c);
1375
1376 return super.toString() +
1377 "[Write locks = " + w + ", Read locks = " + r + "]";
1378 }
1379
1380}