ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/StampedLockTest.java
(Generate patch)

Comparing jsr166/src/test/tck/StampedLockTest.java (file contents):
Revision 1.2 by jsr166, Fri Feb 1 21:44:41 2013 UTC vs.
Revision 1.47 by dl, Tue Jan 26 13:33:06 2021 UTC

# Line 3 | Line 3
3   * with assistance from members of JCP JSR-166 Expert Group and
4   * released to the public domain, as explained at
5   * http://creativecommons.org/publicdomain/zero/1.0/
6 * Other contributors include Andrew Wright, Jeffrey Hayes,
7 * Pat Fisher, Mike Judd.
6   */
7  
8 < import junit.framework.*;
8 > import static java.util.concurrent.TimeUnit.DAYS;
9 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 >
11 > import static java.util.concurrent.locks.StampedLock.isLockStamp;
12 > import static java.util.concurrent.locks.StampedLock.isOptimisticReadStamp;
13 > import static java.util.concurrent.locks.StampedLock.isReadLockStamp;
14 > import static java.util.concurrent.locks.StampedLock.isWriteLockStamp;
15 >
16 > import java.util.ArrayList;
17 > import java.util.List;
18 > import java.util.concurrent.Callable;
19 > import java.util.concurrent.CompletableFuture;
20 > import java.util.concurrent.CountDownLatch;
21 > import java.util.concurrent.Future;
22 > import java.util.concurrent.ThreadLocalRandom;
23 > import java.util.concurrent.TimeUnit;
24   import java.util.concurrent.atomic.AtomicBoolean;
12 import java.util.concurrent.locks.Condition;
25   import java.util.concurrent.locks.Lock;
14 import java.util.concurrent.locks.ReadWriteLock;
26   import java.util.concurrent.locks.StampedLock;
27 < import java.util.concurrent.CountDownLatch;
28 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
29 < import java.util.*;
27 > import java.util.function.BiConsumer;
28 > import java.util.function.Consumer;
29 > import java.util.function.Function;
30 >
31 > import junit.framework.Test;
32 > import junit.framework.TestSuite;
33  
34   public class StampedLockTest extends JSR166TestCase {
35      public static void main(String[] args) {
36 <        junit.textui.TestRunner.run(suite());
36 >        main(suite(), args);
37      }
38      public static Test suite() {
39          return new TestSuite(StampedLockTest.class);
40      }
41  
42 <    // XXXX Just a skeleton implementation for now.
43 <    public void testTODO() { fail("StampedLockTest needs help"); }
42 >    /**
43 >     * Releases write lock, checking isWriteLocked before and after
44 >     */
45 >    void releaseWriteLock(StampedLock lock, long stamp) {
46 >        assertTrue(lock.isWriteLocked());
47 >        assertValid(lock, stamp);
48 >        lock.unlockWrite(stamp);
49 >        assertFalse(lock.isWriteLocked());
50 >        assertFalse(lock.validate(stamp));
51 >    }
52 >
53 >    /**
54 >     * Releases read lock, checking isReadLocked before and after
55 >     */
56 >    void releaseReadLock(StampedLock lock, long stamp) {
57 >        assertTrue(lock.isReadLocked());
58 >        assertValid(lock, stamp);
59 >        lock.unlockRead(stamp);
60 >        assertFalse(lock.isReadLocked());
61 >        assertTrue(lock.validate(stamp));
62 >    }
63 >
64 >    long assertNonZero(long v) {
65 >        assertTrue(v != 0L);
66 >        return v;
67 >    }
68 >
69 >    long assertValid(StampedLock lock, long stamp) {
70 >        assertTrue(stamp != 0L);
71 >        assertTrue(lock.validate(stamp));
72 >        return stamp;
73 >    }
74 >
75 >    void assertUnlocked(StampedLock lock) {
76 >        assertFalse(lock.isReadLocked());
77 >        assertFalse(lock.isWriteLocked());
78 >        assertEquals(0, lock.getReadLockCount());
79 >        assertValid(lock, lock.tryOptimisticRead());
80 >    }
81 >
82 >    List<Action> lockLockers(Lock lock) {
83 >        return List.of(
84 >            () -> lock.lock(),
85 >            () -> lock.lockInterruptibly(),
86 >            () -> lock.tryLock(),
87 >            () -> lock.tryLock(Long.MIN_VALUE, DAYS),
88 >            () -> lock.tryLock(0L, DAYS),
89 >            () -> lock.tryLock(Long.MAX_VALUE, DAYS));
90 >    }
91 >
92 >    List<Function<StampedLock, Long>> readLockers() {
93 >        return List.of(
94 >            sl -> sl.readLock(),
95 >            sl -> sl.tryReadLock(),
96 >            sl -> readLockInterruptiblyUninterrupted(sl),
97 >            sl -> tryReadLockUninterrupted(sl, Long.MIN_VALUE, DAYS),
98 >            sl -> tryReadLockUninterrupted(sl, 0L, DAYS),
99 >            sl -> sl.tryConvertToReadLock(sl.tryOptimisticRead()));
100 >    }
101 >
102 >    List<BiConsumer<StampedLock, Long>> readUnlockers() {
103 >        return List.of(
104 >            (sl, stamp) -> sl.unlockRead(stamp),
105 >            (sl, stamp) -> assertTrue(sl.tryUnlockRead()),
106 >            (sl, stamp) -> sl.asReadLock().unlock(),
107 >            (sl, stamp) -> sl.unlock(stamp),
108 >            (sl, stamp) -> assertValid(sl, sl.tryConvertToOptimisticRead(stamp)));
109 >    }
110 >
111 >    List<Function<StampedLock, Long>> writeLockers() {
112 >        return List.of(
113 >            sl -> sl.writeLock(),
114 >            sl -> sl.tryWriteLock(),
115 >            sl -> writeLockInterruptiblyUninterrupted(sl),
116 >            sl -> tryWriteLockUninterrupted(sl, Long.MIN_VALUE, DAYS),
117 >            sl -> tryWriteLockUninterrupted(sl, 0L, DAYS),
118 >            sl -> sl.tryConvertToWriteLock(sl.tryOptimisticRead()));
119 >    }
120 >
121 >    List<BiConsumer<StampedLock, Long>> writeUnlockers() {
122 >        return List.of(
123 >            (sl, stamp) -> sl.unlockWrite(stamp),
124 >            (sl, stamp) -> assertTrue(sl.tryUnlockWrite()),
125 >            (sl, stamp) -> sl.asWriteLock().unlock(),
126 >            (sl, stamp) -> sl.unlock(stamp),
127 >            (sl, stamp) -> assertValid(sl, sl.tryConvertToOptimisticRead(stamp)));
128 >    }
129 >
130 >    /**
131 >     * Constructed StampedLock is in unlocked state
132 >     */
133 >    public void testConstructor() {
134 >        assertUnlocked(new StampedLock());
135 >    }
136 >
137 >    /**
138 >     * write-locking, then unlocking, an unlocked lock succeed
139 >     */
140 >    public void testWriteLock_lockUnlock() {
141 >        StampedLock lock = new StampedLock();
142 >
143 >        for (Function<StampedLock, Long> writeLocker : writeLockers())
144 >        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
145 >            assertFalse(lock.isWriteLocked());
146 >            assertFalse(lock.isReadLocked());
147 >            assertEquals(0, lock.getReadLockCount());
148 >
149 >            long s = writeLocker.apply(lock);
150 >            assertValid(lock, s);
151 >            assertTrue(lock.isWriteLocked());
152 >            assertFalse(lock.isReadLocked());
153 >            assertEquals(0, lock.getReadLockCount());
154 >            writeUnlocker.accept(lock, s);
155 >            assertUnlocked(lock);
156 >        }
157 >    }
158 >
159 >    /**
160 >     * read-locking, then unlocking, an unlocked lock succeed
161 >     */
162 >    public void testReadLock_lockUnlock() {
163 >        StampedLock lock = new StampedLock();
164 >
165 >        for (Function<StampedLock, Long> readLocker : readLockers())
166 >        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
167 >            long s = 42;
168 >            for (int i = 0; i < 2; i++) {
169 >                s = assertValid(lock, readLocker.apply(lock));
170 >                assertFalse(lock.isWriteLocked());
171 >                assertTrue(lock.isReadLocked());
172 >                assertEquals(i + 1, lock.getReadLockCount());
173 >            }
174 >            for (int i = 0; i < 2; i++) {
175 >                assertFalse(lock.isWriteLocked());
176 >                assertTrue(lock.isReadLocked());
177 >                assertEquals(2 - i, lock.getReadLockCount());
178 >                readUnlocker.accept(lock, s);
179 >            }
180 >            assertUnlocked(lock);
181 >        }
182 >    }
183 >
184 >    /**
185 >     * tryUnlockWrite fails if not write locked
186 >     */
187 >    public void testTryUnlockWrite_failure() {
188 >        StampedLock lock = new StampedLock();
189 >        assertFalse(lock.tryUnlockWrite());
190 >
191 >        for (Function<StampedLock, Long> readLocker : readLockers())
192 >        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
193 >            long s = assertValid(lock, readLocker.apply(lock));
194 >            assertFalse(lock.tryUnlockWrite());
195 >            assertTrue(lock.isReadLocked());
196 >            readUnlocker.accept(lock, s);
197 >            assertUnlocked(lock);
198 >        }
199 >    }
200 >
201 >    /**
202 >     * tryUnlockRead fails if not read locked
203 >     */
204 >    public void testTryUnlockRead_failure() {
205 >        StampedLock lock = new StampedLock();
206 >        assertFalse(lock.tryUnlockRead());
207 >
208 >        for (Function<StampedLock, Long> writeLocker : writeLockers())
209 >        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
210 >            long s = writeLocker.apply(lock);
211 >            assertFalse(lock.tryUnlockRead());
212 >            assertTrue(lock.isWriteLocked());
213 >            writeUnlocker.accept(lock, s);
214 >            assertUnlocked(lock);
215 >        }
216 >    }
217  
218 <    public void testConstructor() { new StampedLock(); }
218 >    /**
219 >     * validate(0L) fails
220 >     */
221 >    public void testValidate0() {
222 >        StampedLock lock = new StampedLock();
223 >        assertFalse(lock.validate(0L));
224 >    }
225 >
226 >    /**
227 >     * A stamp obtained from a successful lock operation validates while the lock is held
228 >     */
229 >    public void testValidate() throws InterruptedException {
230 >        StampedLock lock = new StampedLock();
231 >
232 >        for (Function<StampedLock, Long> readLocker : readLockers())
233 >        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
234 >            long s = assertNonZero(readLocker.apply(lock));
235 >            assertTrue(lock.validate(s));
236 >            readUnlocker.accept(lock, s);
237 >        }
238 >
239 >        for (Function<StampedLock, Long> writeLocker : writeLockers())
240 >        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
241 >            long s = assertNonZero(writeLocker.apply(lock));
242 >            assertTrue(lock.validate(s));
243 >            writeUnlocker.accept(lock, s);
244 >        }
245 >    }
246 >
247 >    /**
248 >     * A stamp obtained from an unsuccessful lock operation does not validate
249 >     */
250 >    public void testValidate2() throws InterruptedException {
251 >        StampedLock lock = new StampedLock();
252 >        long s = assertNonZero(lock.writeLock());
253 >        assertTrue(lock.validate(s));
254 >        assertFalse(lock.validate(lock.tryWriteLock()));
255 >        assertFalse(lock.validate(lock.tryWriteLock(randomExpiredTimeout(),
256 >                                                    randomTimeUnit())));
257 >        assertFalse(lock.validate(lock.tryReadLock()));
258 >        assertFalse(lock.validate(lock.tryWriteLock(randomExpiredTimeout(),
259 >                                                    randomTimeUnit())));
260 >        assertFalse(lock.validate(lock.tryOptimisticRead()));
261 >        lock.unlockWrite(s);
262 >    }
263 >
264 >    void assertThrowInterruptedExceptionWhenPreInterrupted(Action[] actions) {
265 >        for (Action action : actions) {
266 >            Thread.currentThread().interrupt();
267 >            try {
268 >                action.run();
269 >                shouldThrow();
270 >            }
271 >            catch (InterruptedException success) {}
272 >            catch (Throwable fail) { threadUnexpectedException(fail); }
273 >            assertFalse(Thread.interrupted());
274 >        }
275 >    }
276 >
277 >    /**
278 >     * interruptible operations throw InterruptedException when pre-interrupted
279 >     */
280 >    public void testInterruptibleOperationsThrowInterruptedExceptionWhenPreInterrupted() {
281 >        final StampedLock lock = new StampedLock();
282 >
283 >        Action[] interruptibleLockActions = {
284 >            () -> lock.writeLockInterruptibly(),
285 >            () -> lock.tryWriteLock(Long.MIN_VALUE, DAYS),
286 >            () -> lock.tryWriteLock(Long.MAX_VALUE, DAYS),
287 >            () -> lock.readLockInterruptibly(),
288 >            () -> lock.tryReadLock(Long.MIN_VALUE, DAYS),
289 >            () -> lock.tryReadLock(Long.MAX_VALUE, DAYS),
290 >            () -> lock.asWriteLock().lockInterruptibly(),
291 >            () -> lock.asWriteLock().tryLock(0L, DAYS),
292 >            () -> lock.asWriteLock().tryLock(Long.MAX_VALUE, DAYS),
293 >            () -> lock.asReadLock().lockInterruptibly(),
294 >            () -> lock.asReadLock().tryLock(0L, DAYS),
295 >            () -> lock.asReadLock().tryLock(Long.MAX_VALUE, DAYS),
296 >        };
297 >        shuffle(interruptibleLockActions);
298 >
299 >        assertThrowInterruptedExceptionWhenPreInterrupted(interruptibleLockActions);
300 >        {
301 >            long s = lock.writeLock();
302 >            assertThrowInterruptedExceptionWhenPreInterrupted(interruptibleLockActions);
303 >            lock.unlockWrite(s);
304 >        }
305 >        {
306 >            long s = lock.readLock();
307 >            assertThrowInterruptedExceptionWhenPreInterrupted(interruptibleLockActions);
308 >            lock.unlockRead(s);
309 >        }
310 >    }
311 >
312 >    void assertThrowInterruptedExceptionWhenInterrupted(Action[] actions) {
313 >        int n = actions.length;
314 >        Future<?>[] futures = new Future<?>[n];
315 >        CountDownLatch threadsStarted = new CountDownLatch(n);
316 >        CountDownLatch done = new CountDownLatch(n);
317 >
318 >        for (int i = 0; i < n; i++) {
319 >            Action action = actions[i];
320 >            futures[i] = cachedThreadPool.submit(new CheckedRunnable() {
321 >                public void realRun() throws Throwable {
322 >                    threadsStarted.countDown();
323 >                    try {
324 >                        action.run();
325 >                        shouldThrow();
326 >                    }
327 >                    catch (InterruptedException success) {}
328 >                    catch (Throwable fail) { threadUnexpectedException(fail); }
329 >                    assertFalse(Thread.interrupted());
330 >                    done.countDown();
331 >                }});
332 >        }
333 >
334 >        await(threadsStarted);
335 >        assertEquals(n, done.getCount());
336 >        for (Future<?> future : futures) // Interrupt all the tasks
337 >            future.cancel(true);
338 >        await(done);
339 >    }
340 >
341 >    /**
342 >     * interruptible operations throw InterruptedException when write locked and interrupted
343 >     */
344 >    public void testInterruptibleOperationsThrowInterruptedExceptionWriteLockedInterrupted() {
345 >        final StampedLock lock = new StampedLock();
346 >        long stamp = lock.writeLock();
347 >
348 >        Action[] interruptibleLockBlockingActions = {
349 >            () -> lock.writeLockInterruptibly(),
350 >            () -> lock.tryWriteLock(Long.MAX_VALUE, DAYS),
351 >            () -> lock.readLockInterruptibly(),
352 >            () -> lock.tryReadLock(Long.MAX_VALUE, DAYS),
353 >            () -> lock.asWriteLock().lockInterruptibly(),
354 >            () -> lock.asWriteLock().tryLock(Long.MAX_VALUE, DAYS),
355 >            () -> lock.asReadLock().lockInterruptibly(),
356 >            () -> lock.asReadLock().tryLock(Long.MAX_VALUE, DAYS),
357 >        };
358 >        shuffle(interruptibleLockBlockingActions);
359 >
360 >        assertThrowInterruptedExceptionWhenInterrupted(interruptibleLockBlockingActions);
361 >
362 >        releaseWriteLock(lock, stamp);
363 >    }
364 >
365 >    /**
366 >     * interruptible operations throw InterruptedException when read locked and interrupted
367 >     */
368 >    public void testInterruptibleOperationsThrowInterruptedExceptionReadLockedInterrupted() {
369 >        final StampedLock lock = new StampedLock();
370 >        long stamp = lock.readLock();
371 >
372 >        Action[] interruptibleLockBlockingActions = {
373 >            () -> lock.writeLockInterruptibly(),
374 >            () -> lock.tryWriteLock(Long.MAX_VALUE, DAYS),
375 >            () -> lock.asWriteLock().lockInterruptibly(),
376 >            () -> lock.asWriteLock().tryLock(Long.MAX_VALUE, DAYS),
377 >        };
378 >        shuffle(interruptibleLockBlockingActions);
379 >
380 >        assertThrowInterruptedExceptionWhenInterrupted(interruptibleLockBlockingActions);
381 >
382 >        releaseReadLock(lock, stamp);
383 >    }
384 >
385 >    /**
386 >     * Non-interruptible operations ignore and preserve interrupt status
387 >     */
388 >    public void testNonInterruptibleOperationsIgnoreInterrupts() {
389 >        final StampedLock lock = new StampedLock();
390 >        Thread.currentThread().interrupt();
391 >
392 >        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
393 >            long s = assertValid(lock, lock.readLock());
394 >            readUnlocker.accept(lock, s);
395 >            s = assertValid(lock, lock.tryReadLock());
396 >            readUnlocker.accept(lock, s);
397 >        }
398 >
399 >        lock.asReadLock().lock();
400 >        lock.asReadLock().unlock();
401 >
402 >        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
403 >            long s = assertValid(lock, lock.writeLock());
404 >            writeUnlocker.accept(lock, s);
405 >            s = assertValid(lock, lock.tryWriteLock());
406 >            writeUnlocker.accept(lock, s);
407 >        }
408 >
409 >        lock.asWriteLock().lock();
410 >        lock.asWriteLock().unlock();
411 >
412 >        assertTrue(Thread.interrupted());
413 >    }
414 >
415 >    /**
416 >     * tryWriteLock on an unlocked lock succeeds
417 >     */
418 >    public void testTryWriteLock() {
419 >        final StampedLock lock = new StampedLock();
420 >        long s = lock.tryWriteLock();
421 >        assertTrue(s != 0L);
422 >        assertTrue(lock.isWriteLocked());
423 >        assertEquals(0L, lock.tryWriteLock());
424 >        releaseWriteLock(lock, s);
425 >    }
426 >
427 >    /**
428 >     * tryWriteLock fails if locked
429 >     */
430 >    public void testTryWriteLockWhenLocked() {
431 >        final StampedLock lock = new StampedLock();
432 >        long s = lock.writeLock();
433 >        Thread t = newStartedThread(new CheckedRunnable() {
434 >            public void realRun() {
435 >                assertEquals(0L, lock.tryWriteLock());
436 >            }});
437 >
438 >        assertEquals(0L, lock.tryWriteLock());
439 >        awaitTermination(t);
440 >        releaseWriteLock(lock, s);
441 >    }
442 >
443 >    /**
444 >     * tryReadLock fails if write-locked
445 >     */
446 >    public void testTryReadLockWhenLocked() {
447 >        final StampedLock lock = new StampedLock();
448 >        long s = lock.writeLock();
449 >        Thread t = newStartedThread(new CheckedRunnable() {
450 >            public void realRun() {
451 >                assertEquals(0L, lock.tryReadLock());
452 >            }});
453 >
454 >        assertEquals(0L, lock.tryReadLock());
455 >        awaitTermination(t);
456 >        releaseWriteLock(lock, s);
457 >    }
458 >
459 >    /**
460 >     * Multiple threads can hold a read lock when not write-locked
461 >     */
462 >    public void testMultipleReadLocks() {
463 >        final StampedLock lock = new StampedLock();
464 >        final long s = lock.readLock();
465 >        Thread t = newStartedThread(new CheckedRunnable() {
466 >            public void realRun() throws InterruptedException {
467 >                long s2 = lock.tryReadLock();
468 >                assertValid(lock, s2);
469 >                lock.unlockRead(s2);
470 >                long s3 = lock.tryReadLock(LONG_DELAY_MS, MILLISECONDS);
471 >                assertValid(lock, s3);
472 >                lock.unlockRead(s3);
473 >                long s4 = lock.readLock();
474 >                assertValid(lock, s4);
475 >                lock.unlockRead(s4);
476 >                lock.asReadLock().lock();
477 >                lock.asReadLock().unlock();
478 >                lock.asReadLock().lockInterruptibly();
479 >                lock.asReadLock().unlock();
480 >                lock.asReadLock().tryLock(Long.MIN_VALUE, DAYS);
481 >                lock.asReadLock().unlock();
482 >            }});
483 >
484 >        awaitTermination(t);
485 >        lock.unlockRead(s);
486 >    }
487 >
488 >    /**
489 >     * writeLock() succeeds only after a reading thread unlocks
490 >     */
491 >    public void testWriteAfterReadLock() throws InterruptedException {
492 >        final CountDownLatch aboutToLock = new CountDownLatch(1);
493 >        final StampedLock lock = new StampedLock();
494 >        long rs = lock.readLock();
495 >        Thread t = newStartedThread(new CheckedRunnable() {
496 >            public void realRun() {
497 >                aboutToLock.countDown();
498 >                long s = lock.writeLock();
499 >                assertTrue(lock.isWriteLocked());
500 >                assertFalse(lock.isReadLocked());
501 >                lock.unlockWrite(s);
502 >            }});
503 >
504 >        await(aboutToLock);
505 >        assertThreadBlocks(t, Thread.State.WAITING);
506 >        assertFalse(lock.isWriteLocked());
507 >        assertTrue(lock.isReadLocked());
508 >        lock.unlockRead(rs);
509 >        awaitTermination(t);
510 >        assertUnlocked(lock);
511 >    }
512  
513 < //     /**
514 < //      * A runnable calling lockInterruptibly
515 < //      */
516 < //     class InterruptibleLockRunnable extends CheckedRunnable {
517 < //         final ReentrantReadWriteLock lock;
518 < //         InterruptibleLockRunnable(ReentrantReadWriteLock l) { lock = l; }
519 < //         public void realRun() throws InterruptedException {
520 < //             lock.writeLock().lockInterruptibly();
521 < //         }
522 < //     }
523 <
524 < //     /**
525 < //      * A runnable calling lockInterruptibly that expects to be
526 < //      * interrupted
527 < //      */
528 < //     class InterruptedLockRunnable extends CheckedInterruptedRunnable {
529 < //         final ReentrantReadWriteLock lock;
530 < //         InterruptedLockRunnable(ReentrantReadWriteLock l) { lock = l; }
531 < //         public void realRun() throws InterruptedException {
532 < //             lock.writeLock().lockInterruptibly();
533 < //         }
534 < //     }
535 <
536 < //     /**
537 < //      * Subclass to expose protected methods
538 < //      */
539 < //     static class PublicReentrantReadWriteLock extends ReentrantReadWriteLock {
540 < //         PublicReentrantReadWriteLock() { super(); }
541 < //         PublicReentrantReadWriteLock(boolean fair) { super(fair); }
542 < //         public Thread getOwner() {
543 < //             return super.getOwner();
544 < //         }
545 < //         public Collection<Thread> getQueuedThreads() {
546 < //             return super.getQueuedThreads();
547 < //         }
548 < //         public Collection<Thread> getWaitingThreads(Condition c) {
549 < //             return super.getWaitingThreads(c);
550 < //         }
551 < //     }
552 <
553 < //     /**
554 < //      * Releases write lock, checking that it had a hold count of 1.
555 < //      */
556 < //     void releaseWriteLock(PublicReentrantReadWriteLock lock) {
557 < //         ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
558 < //         assertWriteLockedByMoi(lock);
559 < //         assertEquals(1, lock.getWriteHoldCount());
560 < //         writeLock.unlock();
561 < //         assertNotWriteLocked(lock);
562 < //     }
563 <
564 < //     /**
565 < //      * Spin-waits until lock.hasQueuedThread(t) becomes true.
566 < //      */
567 < //     void waitForQueuedThread(PublicReentrantReadWriteLock lock, Thread t) {
568 < //         long startTime = System.nanoTime();
569 < //         while (!lock.hasQueuedThread(t)) {
570 < //             if (millisElapsedSince(startTime) > LONG_DELAY_MS)
571 < //                 throw new AssertionFailedError("timed out");
572 < //             Thread.yield();
573 < //         }
574 < //         assertTrue(t.isAlive());
575 < //         assertTrue(lock.getOwner() != t);
576 < //     }
577 <
578 < //     /**
579 < //      * Checks that lock is not write-locked.
580 < //      */
581 < //     void assertNotWriteLocked(PublicReentrantReadWriteLock lock) {
582 < //         assertFalse(lock.isWriteLocked());
583 < //         assertFalse(lock.isWriteLockedByCurrentThread());
584 < //         assertFalse(lock.writeLock().isHeldByCurrentThread());
585 < //         assertEquals(0, lock.getWriteHoldCount());
586 < //         assertEquals(0, lock.writeLock().getHoldCount());
587 < //         assertNull(lock.getOwner());
588 < //     }
589 <
590 < //     /**
591 < //      * Checks that lock is write-locked by the given thread.
592 < //      */
593 < //     void assertWriteLockedBy(PublicReentrantReadWriteLock lock, Thread t) {
594 < //         assertTrue(lock.isWriteLocked());
595 < //         assertSame(t, lock.getOwner());
596 < //         assertEquals(t == Thread.currentThread(),
597 < //                      lock.isWriteLockedByCurrentThread());
598 < //         assertEquals(t == Thread.currentThread(),
599 < //                      lock.writeLock().isHeldByCurrentThread());
600 < //         assertEquals(t == Thread.currentThread(),
601 < //                      lock.getWriteHoldCount() > 0);
602 < //         assertEquals(t == Thread.currentThread(),
603 < //                      lock.writeLock().getHoldCount() > 0);
604 < //         assertEquals(0, lock.getReadLockCount());
605 < //     }
606 <
607 < //     /**
608 < //      * Checks that lock is write-locked by the current thread.
609 < //      */
610 < //     void assertWriteLockedByMoi(PublicReentrantReadWriteLock lock) {
611 < //         assertWriteLockedBy(lock, Thread.currentThread());
612 < //     }
613 <
614 < //     /**
615 < //      * Checks that condition c has no waiters.
616 < //      */
617 < //     void assertHasNoWaiters(PublicReentrantReadWriteLock lock, Condition c) {
618 < //         assertHasWaiters(lock, c, new Thread[] {});
619 < //     }
620 <
621 < //     /**
622 < //      * Checks that condition c has exactly the given waiter threads.
623 < //      */
624 < //     void assertHasWaiters(PublicReentrantReadWriteLock lock, Condition c,
625 < //                           Thread... threads) {
626 < //         lock.writeLock().lock();
627 < //         assertEquals(threads.length > 0, lock.hasWaiters(c));
628 < //         assertEquals(threads.length, lock.getWaitQueueLength(c));
629 < //         assertEquals(threads.length == 0, lock.getWaitingThreads(c).isEmpty());
630 < //         assertEquals(threads.length, lock.getWaitingThreads(c).size());
631 < //         assertEquals(new HashSet<Thread>(lock.getWaitingThreads(c)),
632 < //                      new HashSet<Thread>(Arrays.asList(threads)));
633 < //         lock.writeLock().unlock();
634 < //     }
635 <
636 < //     enum AwaitMethod { await, awaitTimed, awaitNanos, awaitUntil };
637 <
638 < //     /**
639 < //      * Awaits condition using the specified AwaitMethod.
640 < //      */
641 < //     void await(Condition c, AwaitMethod awaitMethod)
642 < //             throws InterruptedException {
643 < //         switch (awaitMethod) {
644 < //         case await:
645 < //             c.await();
646 < //             break;
647 < //         case awaitTimed:
648 < //             assertTrue(c.await(2 * LONG_DELAY_MS, MILLISECONDS));
649 < //             break;
650 < //         case awaitNanos:
651 < //             long nanosRemaining = c.awaitNanos(MILLISECONDS.toNanos(2 * LONG_DELAY_MS));
652 < //             assertTrue(nanosRemaining > 0);
653 < //             break;
654 < //         case awaitUntil:
655 < //             java.util.Date d = new java.util.Date();
656 < //             assertTrue(c.awaitUntil(new java.util.Date(d.getTime() + 2 * LONG_DELAY_MS)));
657 < //             break;
658 < //         }
659 < //     }
660 <
661 < //     /**
662 < //      * Constructor sets given fairness, and is in unlocked state
663 < //      */
664 < //     public void testConstructor() {
665 < //         PublicReentrantReadWriteLock lock;
666 <
667 < //         lock = new PublicReentrantReadWriteLock();
668 < //         assertFalse(lock.isFair());
669 < //         assertNotWriteLocked(lock);
670 < //         assertEquals(0, lock.getReadLockCount());
671 <
672 < //         lock = new PublicReentrantReadWriteLock(true);
673 < //         assertTrue(lock.isFair());
674 < //         assertNotWriteLocked(lock);
675 < //         assertEquals(0, lock.getReadLockCount());
676 <
677 < //         lock = new PublicReentrantReadWriteLock(false);
678 < //         assertFalse(lock.isFair());
679 < //         assertNotWriteLocked(lock);
680 < //         assertEquals(0, lock.getReadLockCount());
681 < //     }
682 <
683 < //     /**
684 < //      * write-locking and read-locking an unlocked lock succeed
685 < //      */
686 < //     public void testLock()      { testLock(false); }
687 < //     public void testLock_fair() { testLock(true); }
688 < //     public void testLock(boolean fair) {
689 < //         PublicReentrantReadWriteLock lock =
690 < //             new PublicReentrantReadWriteLock(fair);
691 < //         assertNotWriteLocked(lock);
692 < //         lock.writeLock().lock();
693 < //         assertWriteLockedByMoi(lock);
694 < //         lock.writeLock().unlock();
695 < //         assertNotWriteLocked(lock);
696 < //         assertEquals(0, lock.getReadLockCount());
697 < //         lock.readLock().lock();
698 < //         assertNotWriteLocked(lock);
699 < //         assertEquals(1, lock.getReadLockCount());
700 < //         lock.readLock().unlock();
701 < //         assertNotWriteLocked(lock);
702 < //         assertEquals(0, lock.getReadLockCount());
703 < //     }
704 <
705 < //     /**
706 < //      * getWriteHoldCount returns number of recursive holds
707 < //      */
708 < //     public void testGetWriteHoldCount()      { testGetWriteHoldCount(false); }
709 < //     public void testGetWriteHoldCount_fair() { testGetWriteHoldCount(true); }
710 < //     public void testGetWriteHoldCount(boolean fair) {
711 < //         ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
712 < //         for (int i = 1; i <= SIZE; i++) {
713 < //             lock.writeLock().lock();
714 < //             assertEquals(i,lock.getWriteHoldCount());
715 < //         }
716 < //         for (int i = SIZE; i > 0; i--) {
717 < //             lock.writeLock().unlock();
718 < //             assertEquals(i-1,lock.getWriteHoldCount());
719 < //         }
720 < //     }
721 <
722 < //     /**
723 < //      * writelock.getHoldCount returns number of recursive holds
724 < //      */
725 < //     public void testGetHoldCount()      { testGetHoldCount(false); }
726 < //     public void testGetHoldCount_fair() { testGetHoldCount(true); }
727 < //     public void testGetHoldCount(boolean fair) {
728 < //         ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
729 < //         for (int i = 1; i <= SIZE; i++) {
730 < //             lock.writeLock().lock();
731 < //             assertEquals(i,lock.writeLock().getHoldCount());
732 < //         }
733 < //         for (int i = SIZE; i > 0; i--) {
734 < //             lock.writeLock().unlock();
735 < //             assertEquals(i-1,lock.writeLock().getHoldCount());
736 < //         }
737 < //     }
738 <
739 < //     /**
740 < //      * getReadHoldCount returns number of recursive holds
741 < //      */
742 < //     public void testGetReadHoldCount()      { testGetReadHoldCount(false); }
743 < //     public void testGetReadHoldCount_fair() { testGetReadHoldCount(true); }
744 < //     public void testGetReadHoldCount(boolean fair) {
745 < //         ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
746 < //         for (int i = 1; i <= SIZE; i++) {
747 < //             lock.readLock().lock();
748 < //             assertEquals(i,lock.getReadHoldCount());
749 < //         }
750 < //         for (int i = SIZE; i > 0; i--) {
751 < //             lock.readLock().unlock();
752 < //             assertEquals(i-1,lock.getReadHoldCount());
753 < //         }
754 < //     }
755 <
756 < //     /**
757 < //      * write-unlocking an unlocked lock throws IllegalMonitorStateException
758 < //      */
759 < //     public void testWriteUnlock_IMSE()      { testWriteUnlock_IMSE(false); }
760 < //     public void testWriteUnlock_IMSE_fair() { testWriteUnlock_IMSE(true); }
761 < //     public void testWriteUnlock_IMSE(boolean fair) {
762 < //         ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
763 < //         try {
764 < //             lock.writeLock().unlock();
765 < //             shouldThrow();
766 < //         } catch (IllegalMonitorStateException success) {}
767 < //     }
768 <
769 < //     /**
770 < //      * read-unlocking an unlocked lock throws IllegalMonitorStateException
771 < //      */
772 < //     public void testReadUnlock_IMSE()      { testReadUnlock_IMSE(false); }
773 < //     public void testReadUnlock_IMSE_fair() { testReadUnlock_IMSE(true); }
774 < //     public void testReadUnlock_IMSE(boolean fair) {
775 < //         ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
776 < //         try {
777 < //             lock.readLock().unlock();
778 < //             shouldThrow();
779 < //         } catch (IllegalMonitorStateException success) {}
780 < //     }
781 <
782 < //     /**
783 < //      * write-lockInterruptibly is interruptible
784 < //      */
785 < //     public void testWriteLockInterruptibly_Interruptible()      { testWriteLockInterruptibly_Interruptible(false); }
786 < //     public void testWriteLockInterruptibly_Interruptible_fair() { testWriteLockInterruptibly_Interruptible(true); }
787 < //     public void testWriteLockInterruptibly_Interruptible(boolean fair) {
788 < //         final PublicReentrantReadWriteLock lock =
789 < //             new PublicReentrantReadWriteLock(fair);
790 < //         lock.writeLock().lock();
791 < //         Thread t = newStartedThread(new CheckedInterruptedRunnable() {
792 < //             public void realRun() throws InterruptedException {
793 < //                 lock.writeLock().lockInterruptibly();
794 < //             }});
795 <
796 < //         waitForQueuedThread(lock, t);
797 < //         t.interrupt();
798 < //         awaitTermination(t);
799 < //         releaseWriteLock(lock);
800 < //     }
801 <
802 < //     /**
803 < //      * timed write-tryLock is interruptible
804 < //      */
805 < //     public void testWriteTryLock_Interruptible()      { testWriteTryLock_Interruptible(false); }
806 < //     public void testWriteTryLock_Interruptible_fair() { testWriteTryLock_Interruptible(true); }
807 < //     public void testWriteTryLock_Interruptible(boolean fair) {
808 < //         final PublicReentrantReadWriteLock lock =
809 < //             new PublicReentrantReadWriteLock(fair);
810 < //         lock.writeLock().lock();
811 < //         Thread t = newStartedThread(new CheckedInterruptedRunnable() {
812 < //             public void realRun() throws InterruptedException {
813 < //                 lock.writeLock().tryLock(2 * LONG_DELAY_MS, MILLISECONDS);
814 < //             }});
815 <
816 < //         waitForQueuedThread(lock, t);
817 < //         t.interrupt();
818 < //         awaitTermination(t);
819 < //         releaseWriteLock(lock);
820 < //     }
821 <
822 < //     /**
823 < //      * read-lockInterruptibly is interruptible
824 < //      */
825 < //     public void testReadLockInterruptibly_Interruptible()      { testReadLockInterruptibly_Interruptible(false); }
826 < //     public void testReadLockInterruptibly_Interruptible_fair() { testReadLockInterruptibly_Interruptible(true); }
827 < //     public void testReadLockInterruptibly_Interruptible(boolean fair) {
828 < //         final PublicReentrantReadWriteLock lock =
829 < //             new PublicReentrantReadWriteLock(fair);
830 < //         lock.writeLock().lock();
831 < //         Thread t = newStartedThread(new CheckedInterruptedRunnable() {
832 < //             public void realRun() throws InterruptedException {
833 < //                 lock.readLock().lockInterruptibly();
834 < //             }});
835 <
836 < //         waitForQueuedThread(lock, t);
837 < //         t.interrupt();
838 < //         awaitTermination(t);
839 < //         releaseWriteLock(lock);
840 < //     }
841 <
842 < //     /**
843 < //      * timed read-tryLock is interruptible
844 < //      */
845 < //     public void testReadTryLock_Interruptible()      { testReadTryLock_Interruptible(false); }
846 < //     public void testReadTryLock_Interruptible_fair() { testReadTryLock_Interruptible(true); }
847 < //     public void testReadTryLock_Interruptible(boolean fair) {
848 < //         final PublicReentrantReadWriteLock lock =
849 < //             new PublicReentrantReadWriteLock(fair);
850 < //         lock.writeLock().lock();
851 < //         Thread t = newStartedThread(new CheckedInterruptedRunnable() {
852 < //             public void realRun() throws InterruptedException {
853 < //                 lock.readLock().tryLock(2 * LONG_DELAY_MS, MILLISECONDS);
854 < //             }});
855 <
856 < //         waitForQueuedThread(lock, t);
857 < //         t.interrupt();
858 < //         awaitTermination(t);
859 < //         releaseWriteLock(lock);
860 < //     }
861 <
862 < //     /**
863 < //      * write-tryLock on an unlocked lock succeeds
864 < //      */
865 < //     public void testWriteTryLock()      { testWriteTryLock(false); }
866 < //     public void testWriteTryLock_fair() { testWriteTryLock(true); }
867 < //     public void testWriteTryLock(boolean fair) {
868 < //         final PublicReentrantReadWriteLock lock =
869 < //             new PublicReentrantReadWriteLock(fair);
870 < //         assertTrue(lock.writeLock().tryLock());
871 < //         assertWriteLockedByMoi(lock);
872 < //         assertTrue(lock.writeLock().tryLock());
873 < //         assertWriteLockedByMoi(lock);
874 < //         lock.writeLock().unlock();
875 < //         releaseWriteLock(lock);
876 < //     }
877 <
878 < //     /**
879 < //      * write-tryLock fails if locked
880 < //      */
881 < //     public void testWriteTryLockWhenLocked()      { testWriteTryLockWhenLocked(false); }
882 < //     public void testWriteTryLockWhenLocked_fair() { testWriteTryLockWhenLocked(true); }
883 < //     public void testWriteTryLockWhenLocked(boolean fair) {
884 < //         final PublicReentrantReadWriteLock lock =
885 < //             new PublicReentrantReadWriteLock(fair);
886 < //         lock.writeLock().lock();
887 < //         Thread t = newStartedThread(new CheckedRunnable() {
888 < //             public void realRun() {
889 < //                 assertFalse(lock.writeLock().tryLock());
890 < //             }});
891 <
892 < //         awaitTermination(t);
893 < //         releaseWriteLock(lock);
894 < //     }
895 <
896 < //     /**
897 < //      * read-tryLock fails if locked
898 < //      */
899 < //     public void testReadTryLockWhenLocked()      { testReadTryLockWhenLocked(false); }
900 < //     public void testReadTryLockWhenLocked_fair() { testReadTryLockWhenLocked(true); }
901 < //     public void testReadTryLockWhenLocked(boolean fair) {
902 < //         final PublicReentrantReadWriteLock lock =
903 < //             new PublicReentrantReadWriteLock(fair);
904 < //         lock.writeLock().lock();
905 < //         Thread t = newStartedThread(new CheckedRunnable() {
906 < //             public void realRun() {
907 < //                 assertFalse(lock.readLock().tryLock());
908 < //             }});
909 <
910 < //         awaitTermination(t);
911 < //         releaseWriteLock(lock);
912 < //     }
913 <
914 < //     /**
915 < //      * Multiple threads can hold a read lock when not write-locked
916 < //      */
917 < //     public void testMultipleReadLocks()      { testMultipleReadLocks(false); }
918 < //     public void testMultipleReadLocks_fair() { testMultipleReadLocks(true); }
919 < //     public void testMultipleReadLocks(boolean fair) {
920 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
921 < //         lock.readLock().lock();
922 < //         Thread t = newStartedThread(new CheckedRunnable() {
923 < //             public void realRun() throws InterruptedException {
924 < //                 assertTrue(lock.readLock().tryLock());
925 < //                 lock.readLock().unlock();
926 < //                 assertTrue(lock.readLock().tryLock(LONG_DELAY_MS, MILLISECONDS));
927 < //                 lock.readLock().unlock();
928 < //                 lock.readLock().lock();
929 < //                 lock.readLock().unlock();
930 < //             }});
931 <
932 < //         awaitTermination(t);
933 < //         lock.readLock().unlock();
934 < //     }
935 <
936 < //     /**
937 < //      * A writelock succeeds only after a reading thread unlocks
938 < //      */
939 < //     public void testWriteAfterReadLock()      { testWriteAfterReadLock(false); }
940 < //     public void testWriteAfterReadLock_fair() { testWriteAfterReadLock(true); }
941 < //     public void testWriteAfterReadLock(boolean fair) {
942 < //         final PublicReentrantReadWriteLock lock =
943 < //             new PublicReentrantReadWriteLock(fair);
944 < //         lock.readLock().lock();
945 < //         Thread t = newStartedThread(new CheckedRunnable() {
946 < //             public void realRun() {
947 < //                 assertEquals(1, lock.getReadLockCount());
948 < //                 lock.writeLock().lock();
949 < //                 assertEquals(0, lock.getReadLockCount());
950 < //                 lock.writeLock().unlock();
951 < //             }});
952 < //         waitForQueuedThread(lock, t);
953 < //         assertNotWriteLocked(lock);
954 < //         assertEquals(1, lock.getReadLockCount());
955 < //         lock.readLock().unlock();
956 < //         assertEquals(0, lock.getReadLockCount());
957 < //         awaitTermination(t);
958 < //         assertNotWriteLocked(lock);
959 < //     }
960 <
961 < //     /**
962 < //      * A writelock succeeds only after reading threads unlock
963 < //      */
964 < //     public void testWriteAfterMultipleReadLocks()      { testWriteAfterMultipleReadLocks(false); }
965 < //     public void testWriteAfterMultipleReadLocks_fair() { testWriteAfterMultipleReadLocks(true); }
966 < //     public void testWriteAfterMultipleReadLocks(boolean fair) {
967 < //         final PublicReentrantReadWriteLock lock =
968 < //             new PublicReentrantReadWriteLock(fair);
969 < //         lock.readLock().lock();
970 < //         lock.readLock().lock();
971 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
972 < //             public void realRun() {
973 < //                 lock.readLock().lock();
974 < //                 assertEquals(3, lock.getReadLockCount());
975 < //                 lock.readLock().unlock();
976 < //             }});
977 < //         awaitTermination(t1);
978 <
979 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
980 < //             public void realRun() {
981 < //                 assertEquals(2, lock.getReadLockCount());
982 < //                 lock.writeLock().lock();
983 < //                 assertEquals(0, lock.getReadLockCount());
984 < //                 lock.writeLock().unlock();
985 < //             }});
986 < //         waitForQueuedThread(lock, t2);
987 < //         assertNotWriteLocked(lock);
988 < //         assertEquals(2, lock.getReadLockCount());
989 < //         lock.readLock().unlock();
990 < //         lock.readLock().unlock();
991 < //         assertEquals(0, lock.getReadLockCount());
992 < //         awaitTermination(t2);
993 < //         assertNotWriteLocked(lock);
994 < //     }
995 <
996 < //     /**
997 < //      * A thread that tries to acquire a fair read lock (non-reentrantly)
998 < //      * will block if there is a waiting writer thread
999 < //      */
1000 < //     public void testReaderWriterReaderFairFifo() {
1001 < //         final PublicReentrantReadWriteLock lock =
1002 < //             new PublicReentrantReadWriteLock(true);
1003 < //         final AtomicBoolean t1GotLock = new AtomicBoolean(false);
1004 <
1005 < //         lock.readLock().lock();
1006 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
1007 < //             public void realRun() {
1008 < //                 assertEquals(1, lock.getReadLockCount());
1009 < //                 lock.writeLock().lock();
1010 < //                 assertEquals(0, lock.getReadLockCount());
1011 < //                 t1GotLock.set(true);
1012 < //                 lock.writeLock().unlock();
1013 < //             }});
1014 < //         waitForQueuedThread(lock, t1);
1015 <
1016 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
1017 < //             public void realRun() {
1018 < //                 assertEquals(1, lock.getReadLockCount());
1019 < //                 lock.readLock().lock();
1020 < //                 assertEquals(1, lock.getReadLockCount());
1021 < //                 assertTrue(t1GotLock.get());
1022 < //                 lock.readLock().unlock();
1023 < //             }});
1024 < //         waitForQueuedThread(lock, t2);
1025 < //         assertTrue(t1.isAlive());
1026 < //         assertNotWriteLocked(lock);
1027 < //         assertEquals(1, lock.getReadLockCount());
1028 < //         lock.readLock().unlock();
1029 < //         awaitTermination(t1);
1030 < //         awaitTermination(t2);
1031 < //         assertNotWriteLocked(lock);
1032 < //     }
1033 <
1034 < //     /**
1035 < //      * Readlocks succeed only after a writing thread unlocks
1036 < //      */
1037 < //     public void testReadAfterWriteLock()      { testReadAfterWriteLock(false); }
1038 < //     public void testReadAfterWriteLock_fair() { testReadAfterWriteLock(true); }
1039 < //     public void testReadAfterWriteLock(boolean fair) {
1040 < //         final PublicReentrantReadWriteLock lock =
1041 < //             new PublicReentrantReadWriteLock(fair);
1042 < //         lock.writeLock().lock();
1043 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
1044 < //             public void realRun() {
1045 < //                 lock.readLock().lock();
1046 < //                 lock.readLock().unlock();
1047 < //             }});
1048 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
1049 < //             public void realRun() {
1050 < //                 lock.readLock().lock();
1051 < //                 lock.readLock().unlock();
1052 < //             }});
1053 <
1054 < //         waitForQueuedThread(lock, t1);
1055 < //         waitForQueuedThread(lock, t2);
1056 < //         releaseWriteLock(lock);
1057 < //         awaitTermination(t1);
1058 < //         awaitTermination(t2);
1059 < //     }
1060 <
1061 < //     /**
1062 < //      * Read trylock succeeds if write locked by current thread
1063 < //      */
1064 < //     public void testReadHoldingWriteLock()      { testReadHoldingWriteLock(false); }
1065 < //     public void testReadHoldingWriteLock_fair() { testReadHoldingWriteLock(true); }
1066 < //     public void testReadHoldingWriteLock(boolean fair) {
1067 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1068 < //         lock.writeLock().lock();
1069 < //         assertTrue(lock.readLock().tryLock());
1070 < //         lock.readLock().unlock();
1071 < //         lock.writeLock().unlock();
1072 < //     }
1073 <
1074 < //     /**
1075 < //      * Read trylock succeeds (barging) even in the presence of waiting
1076 < //      * readers and/or writers
1077 < //      */
1078 < //     public void testReadTryLockBarging()      { testReadTryLockBarging(false); }
1079 < //     public void testReadTryLockBarging_fair() { testReadTryLockBarging(true); }
1080 < //     public void testReadTryLockBarging(boolean fair) {
1081 < //         final PublicReentrantReadWriteLock lock =
1082 < //             new PublicReentrantReadWriteLock(fair);
1083 < //         lock.readLock().lock();
1084 <
1085 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
1086 < //             public void realRun() {
1087 < //                 lock.writeLock().lock();
1088 < //                 lock.writeLock().unlock();
1089 < //             }});
1090 <
1091 < //         waitForQueuedThread(lock, t1);
1092 <
1093 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
1094 < //             public void realRun() {
1095 < //                 lock.readLock().lock();
1096 < //                 lock.readLock().unlock();
1097 < //             }});
1098 <
1099 < //         if (fair)
1100 < //             waitForQueuedThread(lock, t2);
1101 <
1102 < //         Thread t3 = newStartedThread(new CheckedRunnable() {
1103 < //             public void realRun() {
1104 < //                 lock.readLock().tryLock();
1105 < //                 lock.readLock().unlock();
1106 < //             }});
1107 <
1108 < //         assertTrue(lock.getReadLockCount() > 0);
1109 < //         awaitTermination(t3);
1110 < //         assertTrue(t1.isAlive());
1111 < //         if (fair) assertTrue(t2.isAlive());
1112 < //         lock.readLock().unlock();
1113 < //         awaitTermination(t1);
1114 < //         awaitTermination(t2);
1115 < //     }
1116 <
1117 < //     /**
1118 < //      * Read lock succeeds if write locked by current thread even if
1119 < //      * other threads are waiting for readlock
1120 < //      */
1121 < //     public void testReadHoldingWriteLock2()      { testReadHoldingWriteLock2(false); }
1122 < //     public void testReadHoldingWriteLock2_fair() { testReadHoldingWriteLock2(true); }
1123 < //     public void testReadHoldingWriteLock2(boolean fair) {
1124 < //         final PublicReentrantReadWriteLock lock =
1125 < //             new PublicReentrantReadWriteLock(fair);
1126 < //         lock.writeLock().lock();
1127 < //         lock.readLock().lock();
1128 < //         lock.readLock().unlock();
1129 <
1130 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
1131 < //             public void realRun() {
1132 < //                 lock.readLock().lock();
1133 < //                 lock.readLock().unlock();
1134 < //             }});
1135 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
1136 < //             public void realRun() {
1137 < //                 lock.readLock().lock();
1138 < //                 lock.readLock().unlock();
1139 < //             }});
1140 <
1141 < //         waitForQueuedThread(lock, t1);
1142 < //         waitForQueuedThread(lock, t2);
1143 < //         assertWriteLockedByMoi(lock);
1144 < //         lock.readLock().lock();
1145 < //         lock.readLock().unlock();
1146 < //         releaseWriteLock(lock);
1147 < //         awaitTermination(t1);
1148 < //         awaitTermination(t2);
1149 < //     }
1150 <
1151 < //     /**
1152 < //      * Read lock succeeds if write locked by current thread even if
1153 < //      * other threads are waiting for writelock
1154 < //      */
1155 < //     public void testReadHoldingWriteLock3()      { testReadHoldingWriteLock3(false); }
1156 < //     public void testReadHoldingWriteLock3_fair() { testReadHoldingWriteLock3(true); }
1157 < //     public void testReadHoldingWriteLock3(boolean fair) {
1158 < //         final PublicReentrantReadWriteLock lock =
1159 < //             new PublicReentrantReadWriteLock(fair);
1160 < //         lock.writeLock().lock();
1161 < //         lock.readLock().lock();
1162 < //         lock.readLock().unlock();
1163 <
1164 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
1165 < //             public void realRun() {
1166 < //                 lock.writeLock().lock();
1167 < //                 lock.writeLock().unlock();
1168 < //             }});
1169 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
1170 < //             public void realRun() {
1171 < //                 lock.writeLock().lock();
1172 < //                 lock.writeLock().unlock();
1173 < //             }});
1174 <
1175 < //         waitForQueuedThread(lock, t1);
1176 < //         waitForQueuedThread(lock, t2);
1177 < //         assertWriteLockedByMoi(lock);
1178 < //         lock.readLock().lock();
1179 < //         lock.readLock().unlock();
1180 < //         assertWriteLockedByMoi(lock);
1181 < //         lock.writeLock().unlock();
1182 < //         awaitTermination(t1);
1183 < //         awaitTermination(t2);
1184 < //     }
1185 <
1186 < //     /**
1187 < //      * Write lock succeeds if write locked by current thread even if
1188 < //      * other threads are waiting for writelock
1189 < //      */
1190 < //     public void testWriteHoldingWriteLock4()      { testWriteHoldingWriteLock4(false); }
1191 < //     public void testWriteHoldingWriteLock4_fair() { testWriteHoldingWriteLock4(true); }
1192 < //     public void testWriteHoldingWriteLock4(boolean fair) {
1193 < //         final PublicReentrantReadWriteLock lock =
1194 < //             new PublicReentrantReadWriteLock(fair);
1195 < //         lock.writeLock().lock();
1196 < //         lock.writeLock().lock();
1197 < //         lock.writeLock().unlock();
1198 <
1199 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
1200 < //             public void realRun() {
1201 < //                 lock.writeLock().lock();
1202 < //                 lock.writeLock().unlock();
1203 < //             }});
1204 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
1205 < //             public void realRun() {
1206 < //                 lock.writeLock().lock();
1207 < //                 lock.writeLock().unlock();
1208 < //             }});
1209 <
1210 < //         waitForQueuedThread(lock, t1);
1211 < //         waitForQueuedThread(lock, t2);
1212 < //         assertWriteLockedByMoi(lock);
1213 < //         assertEquals(1, lock.getWriteHoldCount());
1214 < //         lock.writeLock().lock();
1215 < //         assertWriteLockedByMoi(lock);
1216 < //         assertEquals(2, lock.getWriteHoldCount());
1217 < //         lock.writeLock().unlock();
1218 < //         assertWriteLockedByMoi(lock);
1219 < //         assertEquals(1, lock.getWriteHoldCount());
1220 < //         lock.writeLock().unlock();
1221 < //         awaitTermination(t1);
1222 < //         awaitTermination(t2);
1223 < //     }
1224 <
1225 < //     /**
1226 < //      * Read tryLock succeeds if readlocked but not writelocked
1227 < //      */
1228 < //     public void testTryLockWhenReadLocked()      { testTryLockWhenReadLocked(false); }
1229 < //     public void testTryLockWhenReadLocked_fair() { testTryLockWhenReadLocked(true); }
1230 < //     public void testTryLockWhenReadLocked(boolean fair) {
1231 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1232 < //         lock.readLock().lock();
1233 < //         Thread t = newStartedThread(new CheckedRunnable() {
1234 < //             public void realRun() {
1235 < //                 assertTrue(lock.readLock().tryLock());
1236 < //                 lock.readLock().unlock();
1237 < //             }});
1238 <
1239 < //         awaitTermination(t);
1240 < //         lock.readLock().unlock();
1241 < //     }
1242 <
1243 < //     /**
1244 < //      * write tryLock fails when readlocked
1245 < //      */
1246 < //     public void testWriteTryLockWhenReadLocked()      { testWriteTryLockWhenReadLocked(false); }
1247 < //     public void testWriteTryLockWhenReadLocked_fair() { testWriteTryLockWhenReadLocked(true); }
1248 < //     public void testWriteTryLockWhenReadLocked(boolean fair) {
1249 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1250 < //         lock.readLock().lock();
1251 < //         Thread t = newStartedThread(new CheckedRunnable() {
1252 < //             public void realRun() {
1253 < //                 assertFalse(lock.writeLock().tryLock());
1254 < //             }});
1255 <
1256 < //         awaitTermination(t);
1257 < //         lock.readLock().unlock();
1258 < //     }
1259 <
1260 < //     /**
1261 < //      * write timed tryLock times out if locked
1262 < //      */
1263 < //     public void testWriteTryLock_Timeout()      { testWriteTryLock_Timeout(false); }
1264 < //     public void testWriteTryLock_Timeout_fair() { testWriteTryLock_Timeout(true); }
1265 < //     public void testWriteTryLock_Timeout(boolean fair) {
1266 < //         final PublicReentrantReadWriteLock lock =
1267 < //             new PublicReentrantReadWriteLock(fair);
1268 < //         lock.writeLock().lock();
1269 < //         Thread t = newStartedThread(new CheckedRunnable() {
1270 < //             public void realRun() throws InterruptedException {
1271 < //                 long startTime = System.nanoTime();
1272 < //                 long timeoutMillis = 10;
1273 < //                 assertFalse(lock.writeLock().tryLock(timeoutMillis, MILLISECONDS));
1274 < //                 assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1275 < //             }});
1276 <
1277 < //         awaitTermination(t);
1278 < //         releaseWriteLock(lock);
1279 < //     }
1280 <
1281 < //     /**
1282 < //      * read timed tryLock times out if write-locked
1283 < //      */
1284 < //     public void testReadTryLock_Timeout()      { testReadTryLock_Timeout(false); }
1285 < //     public void testReadTryLock_Timeout_fair() { testReadTryLock_Timeout(true); }
1286 < //     public void testReadTryLock_Timeout(boolean fair) {
1287 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1288 < //         lock.writeLock().lock();
1289 < //         Thread t = newStartedThread(new CheckedRunnable() {
1290 < //             public void realRun() throws InterruptedException {
1291 < //                 long startTime = System.nanoTime();
1292 < //                 long timeoutMillis = 10;
1293 < //                 assertFalse(lock.readLock().tryLock(timeoutMillis, MILLISECONDS));
1294 < //                 assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1295 < //             }});
1296 <
1297 < //         awaitTermination(t);
1298 < //         assertTrue(lock.writeLock().isHeldByCurrentThread());
1299 < //         lock.writeLock().unlock();
1300 < //     }
1301 <
1302 < //     /**
1303 < //      * write lockInterruptibly succeeds if unlocked, else is interruptible
1304 < //      */
1305 < //     public void testWriteLockInterruptibly()      { testWriteLockInterruptibly(false); }
1306 < //     public void testWriteLockInterruptibly_fair() { testWriteLockInterruptibly(true); }
1307 < //     public void testWriteLockInterruptibly(boolean fair) {
1308 < //         final PublicReentrantReadWriteLock lock =
1309 < //             new PublicReentrantReadWriteLock(fair);
1310 < //         try {
1311 < //             lock.writeLock().lockInterruptibly();
1312 < //         } catch (InterruptedException ie) {
1313 < //             threadUnexpectedException(ie);
1314 < //         }
1315 < //         Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1316 < //             public void realRun() throws InterruptedException {
1317 < //                 lock.writeLock().lockInterruptibly();
1318 < //             }});
1319 <
1320 < //         waitForQueuedThread(lock, t);
1321 < //         t.interrupt();
1322 < //         assertTrue(lock.writeLock().isHeldByCurrentThread());
1323 < //         awaitTermination(t);
1324 < //         releaseWriteLock(lock);
1325 < //     }
1326 <
1327 < //     /**
1328 < //      * read lockInterruptibly succeeds if lock free else is interruptible
1329 < //      */
1330 < //     public void testReadLockInterruptibly()      { testReadLockInterruptibly(false); }
1331 < //     public void testReadLockInterruptibly_fair() { testReadLockInterruptibly(true); }
1332 < //     public void testReadLockInterruptibly(boolean fair) {
1333 < //         final PublicReentrantReadWriteLock lock =
1334 < //             new PublicReentrantReadWriteLock(fair);
1335 < //         try {
1336 < //             lock.readLock().lockInterruptibly();
1337 < //             lock.readLock().unlock();
1338 < //             lock.writeLock().lockInterruptibly();
1339 < //         } catch (InterruptedException ie) {
1340 < //             threadUnexpectedException(ie);
1341 < //         }
1342 < //         Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1343 < //             public void realRun() throws InterruptedException {
1344 < //                 lock.readLock().lockInterruptibly();
1345 < //             }});
1346 <
1347 < //         waitForQueuedThread(lock, t);
1348 < //         t.interrupt();
1349 < //         awaitTermination(t);
1350 < //         releaseWriteLock(lock);
1351 < //     }
1352 <
1353 < //     /**
1354 < //      * Calling await without holding lock throws IllegalMonitorStateException
1355 < //      */
1356 < //     public void testAwait_IMSE()      { testAwait_IMSE(false); }
1357 < //     public void testAwait_IMSE_fair() { testAwait_IMSE(true); }
1358 < //     public void testAwait_IMSE(boolean fair) {
1359 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1360 < //         final Condition c = lock.writeLock().newCondition();
1361 < //         for (AwaitMethod awaitMethod : AwaitMethod.values()) {
1362 < //             long startTime = System.nanoTime();
1363 < //             try {
1364 < //                 await(c, awaitMethod);
1365 < //                 shouldThrow();
1366 < //             } catch (IllegalMonitorStateException success) {
1367 < //             } catch (InterruptedException e) { threadUnexpectedException(e); }
1368 < //             assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1369 < //         }
1370 < //     }
1371 <
1372 < //     /**
1373 < //      * Calling signal without holding lock throws IllegalMonitorStateException
1374 < //      */
1375 < //     public void testSignal_IMSE()      { testSignal_IMSE(false); }
1376 < //     public void testSignal_IMSE_fair() { testSignal_IMSE(true); }
1377 < //     public void testSignal_IMSE(boolean fair) {
1378 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1379 < //         final Condition c = lock.writeLock().newCondition();
1380 < //         try {
1381 < //             c.signal();
1382 < //             shouldThrow();
1383 < //         } catch (IllegalMonitorStateException success) {}
1384 < //     }
1385 <
1386 < //     /**
1387 < //      * Calling signalAll without holding lock throws IllegalMonitorStateException
1388 < //      */
1389 < //     public void testSignalAll_IMSE()      { testSignalAll_IMSE(false); }
1390 < //     public void testSignalAll_IMSE_fair() { testSignalAll_IMSE(true); }
1391 < //     public void testSignalAll_IMSE(boolean fair) {
1392 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1393 < //         final Condition c = lock.writeLock().newCondition();
1394 < //         try {
1395 < //             c.signalAll();
1396 < //             shouldThrow();
1397 < //         } catch (IllegalMonitorStateException success) {}
1398 < //     }
1399 <
1400 < //     /**
1401 < //      * awaitNanos without a signal times out
1402 < //      */
1403 < //     public void testAwaitNanos_Timeout()      { testAwaitNanos_Timeout(false); }
1404 < //     public void testAwaitNanos_Timeout_fair() { testAwaitNanos_Timeout(true); }
1405 < //     public void testAwaitNanos_Timeout(boolean fair) {
1406 < //         try {
1407 < //             final ReentrantReadWriteLock lock =
1408 < //                 new ReentrantReadWriteLock(fair);
1409 < //             final Condition c = lock.writeLock().newCondition();
1410 < //             lock.writeLock().lock();
1411 < //             long startTime = System.nanoTime();
1412 < //             long timeoutMillis = 10;
1413 < //             long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
1414 < //             long nanosRemaining = c.awaitNanos(timeoutNanos);
1415 < //             assertTrue(nanosRemaining <= 0);
1416 < //             assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1417 < //             lock.writeLock().unlock();
1418 < //         } catch (InterruptedException e) {
1419 < //             threadUnexpectedException(e);
1420 < //         }
1421 < //     }
1422 <
1423 < //     /**
1424 < //      * timed await without a signal times out
1425 < //      */
1426 < //     public void testAwait_Timeout()      { testAwait_Timeout(false); }
1427 < //     public void testAwait_Timeout_fair() { testAwait_Timeout(true); }
1428 < //     public void testAwait_Timeout(boolean fair) {
1429 < //         try {
1430 < //             final ReentrantReadWriteLock lock =
1431 < //                 new ReentrantReadWriteLock(fair);
1432 < //             final Condition c = lock.writeLock().newCondition();
1433 < //             lock.writeLock().lock();
1434 < //             long startTime = System.nanoTime();
1435 < //             long timeoutMillis = 10;
1436 < //             assertFalse(c.await(timeoutMillis, MILLISECONDS));
1437 < //             assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1438 < //             lock.writeLock().unlock();
1439 < //         } catch (InterruptedException e) {
1440 < //             threadUnexpectedException(e);
1441 < //         }
1442 < //     }
1443 <
1444 < //     /**
1445 < //      * awaitUntil without a signal times out
1446 < //      */
1447 < //     public void testAwaitUntil_Timeout()      { testAwaitUntil_Timeout(false); }
1448 < //     public void testAwaitUntil_Timeout_fair() { testAwaitUntil_Timeout(true); }
1449 < //     public void testAwaitUntil_Timeout(boolean fair) {
1450 < //         try {
1451 < //             final ReentrantReadWriteLock lock =
1452 < //                 new ReentrantReadWriteLock(fair);
1453 < //             final Condition c = lock.writeLock().newCondition();
1454 < //             lock.writeLock().lock();
1455 < //             long startTime = System.nanoTime();
1456 < //             long timeoutMillis = 10;
1457 < //             java.util.Date d = new java.util.Date();
1458 < //             assertFalse(c.awaitUntil(new java.util.Date(d.getTime() + timeoutMillis)));
1459 < //             assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1460 < //             lock.writeLock().unlock();
1461 < //         } catch (InterruptedException e) {
1462 < //             threadUnexpectedException(e);
1463 < //         }
1464 < //     }
1465 <
1466 < //     /**
1467 < //      * await returns when signalled
1468 < //      */
1469 < //     public void testAwait()      { testAwait(false); }
1470 < //     public void testAwait_fair() { testAwait(true); }
1471 < //     public void testAwait(boolean fair) {
1472 < //         final PublicReentrantReadWriteLock lock =
1473 < //             new PublicReentrantReadWriteLock(fair);
1474 < //         final Condition c = lock.writeLock().newCondition();
1475 < //         final CountDownLatch locked = new CountDownLatch(1);
1476 < //         Thread t = newStartedThread(new CheckedRunnable() {
1477 < //             public void realRun() throws InterruptedException {
1478 < //                 lock.writeLock().lock();
1479 < //                 locked.countDown();
1480 < //                 c.await();
1481 < //                 lock.writeLock().unlock();
1482 < //             }});
1483 <
1484 < //         await(locked);
1485 < //         lock.writeLock().lock();
1486 < //         assertHasWaiters(lock, c, t);
1487 < //         c.signal();
1488 < //         assertHasNoWaiters(lock, c);
1489 < //         assertTrue(t.isAlive());
1490 < //         lock.writeLock().unlock();
1491 < //         awaitTermination(t);
1492 < //     }
1493 <
1494 < //     /**
1495 < //      * awaitUninterruptibly is uninterruptible
1496 < //      */
1497 < //     public void testAwaitUninterruptibly()      { testAwaitUninterruptibly(false); }
1498 < //     public void testAwaitUninterruptibly_fair() { testAwaitUninterruptibly(true); }
1499 < //     public void testAwaitUninterruptibly(boolean fair) {
1500 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1501 < //         final Condition c = lock.writeLock().newCondition();
1022 < //         final CountDownLatch pleaseInterrupt = new CountDownLatch(2);
1023 <
1024 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
1025 < //             public void realRun() {
1026 < //                 // Interrupt before awaitUninterruptibly
1027 < //                 lock.writeLock().lock();
1028 < //                 pleaseInterrupt.countDown();
1029 < //                 Thread.currentThread().interrupt();
1030 < //                 c.awaitUninterruptibly();
1031 < //                 assertTrue(Thread.interrupted());
1032 < //                 lock.writeLock().unlock();
1033 < //             }});
1034 <
1035 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
1036 < //             public void realRun() {
1037 < //                 // Interrupt during awaitUninterruptibly
1038 < //                 lock.writeLock().lock();
1039 < //                 pleaseInterrupt.countDown();
1040 < //                 c.awaitUninterruptibly();
1041 < //                 assertTrue(Thread.interrupted());
1042 < //                 lock.writeLock().unlock();
1043 < //             }});
1044 <
1045 < //         await(pleaseInterrupt);
1046 < //         lock.writeLock().lock();
1047 < //         lock.writeLock().unlock();
1048 < //         t2.interrupt();
1049 <
1050 < //         assertThreadStaysAlive(t1);
1051 < //         assertTrue(t2.isAlive());
1052 <
1053 < //         lock.writeLock().lock();
1054 < //         c.signalAll();
1055 < //         lock.writeLock().unlock();
1056 <
1057 < //         awaitTermination(t1);
1058 < //         awaitTermination(t2);
1059 < //     }
1060 <
1061 < //     /**
1062 < //      * await/awaitNanos/awaitUntil is interruptible
1063 < //      */
1064 < //     public void testInterruptible_await()           { testInterruptible(false, AwaitMethod.await); }
1065 < //     public void testInterruptible_await_fair()      { testInterruptible(true,  AwaitMethod.await); }
1066 < //     public void testInterruptible_awaitTimed()      { testInterruptible(false, AwaitMethod.awaitTimed); }
1067 < //     public void testInterruptible_awaitTimed_fair() { testInterruptible(true,  AwaitMethod.awaitTimed); }
1068 < //     public void testInterruptible_awaitNanos()      { testInterruptible(false, AwaitMethod.awaitNanos); }
1069 < //     public void testInterruptible_awaitNanos_fair() { testInterruptible(true,  AwaitMethod.awaitNanos); }
1070 < //     public void testInterruptible_awaitUntil()      { testInterruptible(false, AwaitMethod.awaitUntil); }
1071 < //     public void testInterruptible_awaitUntil_fair() { testInterruptible(true,  AwaitMethod.awaitUntil); }
1072 < //     public void testInterruptible(boolean fair, final AwaitMethod awaitMethod) {
1073 < //         final PublicReentrantReadWriteLock lock =
1074 < //             new PublicReentrantReadWriteLock(fair);
1075 < //         final Condition c = lock.writeLock().newCondition();
1076 < //         final CountDownLatch locked = new CountDownLatch(1);
1077 < //         Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1078 < //             public void realRun() throws InterruptedException {
1079 < //                 lock.writeLock().lock();
1080 < //                 assertWriteLockedByMoi(lock);
1081 < //                 assertHasNoWaiters(lock, c);
1082 < //                 locked.countDown();
1083 < //                 try {
1084 < //                     await(c, awaitMethod);
1085 < //                 } finally {
1086 < //                     assertWriteLockedByMoi(lock);
1087 < //                     assertHasNoWaiters(lock, c);
1088 < //                     lock.writeLock().unlock();
1089 < //                     assertFalse(Thread.interrupted());
1090 < //                 }
1091 < //             }});
1092 <
1093 < //         await(locked);
1094 < //         assertHasWaiters(lock, c, t);
1095 < //         t.interrupt();
1096 < //         awaitTermination(t);
1097 < //         assertNotWriteLocked(lock);
1098 < //     }
1099 <
1100 < //     /**
1101 < //      * signalAll wakes up all threads
1102 < //      */
1103 < //     public void testSignalAll_await()           { testSignalAll(false, AwaitMethod.await); }
1104 < //     public void testSignalAll_await_fair()      { testSignalAll(true,  AwaitMethod.await); }
1105 < //     public void testSignalAll_awaitTimed()      { testSignalAll(false, AwaitMethod.awaitTimed); }
1106 < //     public void testSignalAll_awaitTimed_fair() { testSignalAll(true,  AwaitMethod.awaitTimed); }
1107 < //     public void testSignalAll_awaitNanos()      { testSignalAll(false, AwaitMethod.awaitNanos); }
1108 < //     public void testSignalAll_awaitNanos_fair() { testSignalAll(true,  AwaitMethod.awaitNanos); }
1109 < //     public void testSignalAll_awaitUntil()      { testSignalAll(false, AwaitMethod.awaitUntil); }
1110 < //     public void testSignalAll_awaitUntil_fair() { testSignalAll(true,  AwaitMethod.awaitUntil); }
1111 < //     public void testSignalAll(boolean fair, final AwaitMethod awaitMethod) {
1112 < //         final PublicReentrantReadWriteLock lock =
1113 < //             new PublicReentrantReadWriteLock(fair);
1114 < //         final Condition c = lock.writeLock().newCondition();
1115 < //         final CountDownLatch locked = new CountDownLatch(2);
1116 < //         final Lock writeLock = lock.writeLock();
1117 < //         class Awaiter extends CheckedRunnable {
1118 < //             public void realRun() throws InterruptedException {
1119 < //                 writeLock.lock();
1120 < //                 locked.countDown();
1121 < //                 await(c, awaitMethod);
1122 < //                 writeLock.unlock();
1123 < //             }
1124 < //         }
1125 <
1126 < //         Thread t1 = newStartedThread(new Awaiter());
1127 < //         Thread t2 = newStartedThread(new Awaiter());
1128 <
1129 < //         await(locked);
1130 < //         writeLock.lock();
1131 < //         assertHasWaiters(lock, c, t1, t2);
1132 < //         c.signalAll();
1133 < //         assertHasNoWaiters(lock, c);
1134 < //         writeLock.unlock();
1135 < //         awaitTermination(t1);
1136 < //         awaitTermination(t2);
1137 < //     }
1138 <
1139 < //     /**
1140 < //      * signal wakes up waiting threads in FIFO order
1141 < //      */
1142 < //     public void testSignalWakesFifo()      { testSignalWakesFifo(false); }
1143 < //     public void testSignalWakesFifo_fair() { testSignalWakesFifo(true); }
1144 < //     public void testSignalWakesFifo(boolean fair) {
1145 < //         final PublicReentrantReadWriteLock lock =
1146 < //             new PublicReentrantReadWriteLock(fair);
1147 < //         final Condition c = lock.writeLock().newCondition();
1148 < //         final CountDownLatch locked1 = new CountDownLatch(1);
1149 < //         final CountDownLatch locked2 = new CountDownLatch(1);
1150 < //         final Lock writeLock = lock.writeLock();
1151 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
1152 < //             public void realRun() throws InterruptedException {
1153 < //                 writeLock.lock();
1154 < //                 locked1.countDown();
1155 < //                 c.await();
1156 < //                 writeLock.unlock();
1157 < //             }});
1158 <
1159 < //         await(locked1);
1160 <
1161 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
1162 < //             public void realRun() throws InterruptedException {
1163 < //                 writeLock.lock();
1164 < //                 locked2.countDown();
1165 < //                 c.await();
1166 < //                 writeLock.unlock();
1167 < //             }});
1168 <
1169 < //         await(locked2);
1170 <
1171 < //         writeLock.lock();
1172 < //         assertHasWaiters(lock, c, t1, t2);
1173 < //         assertFalse(lock.hasQueuedThreads());
1174 < //         c.signal();
1175 < //         assertHasWaiters(lock, c, t2);
1176 < //         assertTrue(lock.hasQueuedThread(t1));
1177 < //         assertFalse(lock.hasQueuedThread(t2));
1178 < //         c.signal();
1179 < //         assertHasNoWaiters(lock, c);
1180 < //         assertTrue(lock.hasQueuedThread(t1));
1181 < //         assertTrue(lock.hasQueuedThread(t2));
1182 < //         writeLock.unlock();
1183 < //         awaitTermination(t1);
1184 < //         awaitTermination(t2);
1185 < //     }
1186 <
1187 < //     /**
1188 < //      * await after multiple reentrant locking preserves lock count
1189 < //      */
1190 < //     public void testAwaitLockCount()      { testAwaitLockCount(false); }
1191 < //     public void testAwaitLockCount_fair() { testAwaitLockCount(true); }
1192 < //     public void testAwaitLockCount(boolean fair) {
1193 < //         final PublicReentrantReadWriteLock lock =
1194 < //             new PublicReentrantReadWriteLock(fair);
1195 < //         final Condition c = lock.writeLock().newCondition();
1196 < //         final CountDownLatch locked = new CountDownLatch(2);
1197 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
1198 < //             public void realRun() throws InterruptedException {
1199 < //                 lock.writeLock().lock();
1200 < //                 assertWriteLockedByMoi(lock);
1201 < //                 assertEquals(1, lock.writeLock().getHoldCount());
1202 < //                 locked.countDown();
1203 < //                 c.await();
1204 < //                 assertWriteLockedByMoi(lock);
1205 < //                 assertEquals(1, lock.writeLock().getHoldCount());
1206 < //                 lock.writeLock().unlock();
1207 < //             }});
1208 <
1209 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
1210 < //             public void realRun() throws InterruptedException {
1211 < //                 lock.writeLock().lock();
1212 < //                 lock.writeLock().lock();
1213 < //                 assertWriteLockedByMoi(lock);
1214 < //                 assertEquals(2, lock.writeLock().getHoldCount());
1215 < //                 locked.countDown();
1216 < //                 c.await();
1217 < //                 assertWriteLockedByMoi(lock);
1218 < //                 assertEquals(2, lock.writeLock().getHoldCount());
1219 < //                 lock.writeLock().unlock();
1220 < //                 lock.writeLock().unlock();
1221 < //             }});
1222 <
1223 < //         await(locked);
1224 < //         lock.writeLock().lock();
1225 < //         assertHasWaiters(lock, c, t1, t2);
1226 < //         c.signalAll();
1227 < //         assertHasNoWaiters(lock, c);
1228 < //         lock.writeLock().unlock();
1229 < //         awaitTermination(t1);
1230 < //         awaitTermination(t2);
1231 < //     }
1232 <
1233 < //     /**
1234 < //      * A serialized lock deserializes as unlocked
1235 < //      */
1236 < //     public void testSerialization()      { testSerialization(false); }
1237 < //     public void testSerialization_fair() { testSerialization(true); }
1238 < //     public void testSerialization(boolean fair) {
1239 < //         ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1240 < //         lock.writeLock().lock();
1241 < //         lock.readLock().lock();
1242 <
1243 < //         ReentrantReadWriteLock clone = serialClone(lock);
1244 < //         assertEquals(lock.isFair(), clone.isFair());
1245 < //         assertTrue(lock.isWriteLocked());
1246 < //         assertFalse(clone.isWriteLocked());
1247 < //         assertEquals(1, lock.getReadLockCount());
1248 < //         assertEquals(0, clone.getReadLockCount());
1249 < //         clone.writeLock().lock();
1250 < //         clone.readLock().lock();
1251 < //         assertTrue(clone.isWriteLocked());
1252 < //         assertEquals(1, clone.getReadLockCount());
1253 < //         clone.readLock().unlock();
1254 < //         clone.writeLock().unlock();
1255 < //         assertFalse(clone.isWriteLocked());
1256 < //         assertEquals(1, lock.getReadLockCount());
1257 < //         assertEquals(0, clone.getReadLockCount());
1258 < //     }
1259 <
1260 < //     /**
1261 < //      * hasQueuedThreads reports whether there are waiting threads
1262 < //      */
1263 < //     public void testHasQueuedThreads()      { testHasQueuedThreads(false); }
1264 < //     public void testHasQueuedThreads_fair() { testHasQueuedThreads(true); }
1265 < //     public void testHasQueuedThreads(boolean fair) {
1266 < //         final PublicReentrantReadWriteLock lock =
1267 < //             new PublicReentrantReadWriteLock(fair);
1268 < //         Thread t1 = new Thread(new InterruptedLockRunnable(lock));
1269 < //         Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
1270 < //         assertFalse(lock.hasQueuedThreads());
1271 < //         lock.writeLock().lock();
1272 < //         assertFalse(lock.hasQueuedThreads());
1273 < //         t1.start();
1274 < //         waitForQueuedThread(lock, t1);
1275 < //         assertTrue(lock.hasQueuedThreads());
1276 < //         t2.start();
1277 < //         waitForQueuedThread(lock, t2);
1278 < //         assertTrue(lock.hasQueuedThreads());
1279 < //         t1.interrupt();
1280 < //         awaitTermination(t1);
1281 < //         assertTrue(lock.hasQueuedThreads());
1282 < //         lock.writeLock().unlock();
1283 < //         awaitTermination(t2);
1284 < //         assertFalse(lock.hasQueuedThreads());
1285 < //     }
1286 <
1287 < //     /**
1288 < //      * hasQueuedThread(null) throws NPE
1289 < //      */
1290 < //     public void testHasQueuedThreadNPE()      { testHasQueuedThreadNPE(false); }
1291 < //     public void testHasQueuedThreadNPE_fair() { testHasQueuedThreadNPE(true); }
1292 < //     public void testHasQueuedThreadNPE(boolean fair) {
1293 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1294 < //         try {
1295 < //             lock.hasQueuedThread(null);
1296 < //             shouldThrow();
1297 < //         } catch (NullPointerException success) {}
1298 < //     }
1299 <
1300 < //     /**
1301 < //      * hasQueuedThread reports whether a thread is queued
1302 < //      */
1303 < //     public void testHasQueuedThread()      { testHasQueuedThread(false); }
1304 < //     public void testHasQueuedThread_fair() { testHasQueuedThread(true); }
1305 < //     public void testHasQueuedThread(boolean fair) {
1306 < //         final PublicReentrantReadWriteLock lock =
1307 < //             new PublicReentrantReadWriteLock(fair);
1308 < //         Thread t1 = new Thread(new InterruptedLockRunnable(lock));
1309 < //         Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
1310 < //         assertFalse(lock.hasQueuedThread(t1));
1311 < //         assertFalse(lock.hasQueuedThread(t2));
1312 < //         lock.writeLock().lock();
1313 < //         t1.start();
1314 < //         waitForQueuedThread(lock, t1);
1315 < //         assertTrue(lock.hasQueuedThread(t1));
1316 < //         assertFalse(lock.hasQueuedThread(t2));
1317 < //         t2.start();
1318 < //         waitForQueuedThread(lock, t2);
1319 < //         assertTrue(lock.hasQueuedThread(t1));
1320 < //         assertTrue(lock.hasQueuedThread(t2));
1321 < //         t1.interrupt();
1322 < //         awaitTermination(t1);
1323 < //         assertFalse(lock.hasQueuedThread(t1));
1324 < //         assertTrue(lock.hasQueuedThread(t2));
1325 < //         lock.writeLock().unlock();
1326 < //         awaitTermination(t2);
1327 < //         assertFalse(lock.hasQueuedThread(t1));
1328 < //         assertFalse(lock.hasQueuedThread(t2));
1329 < //     }
1330 <
1331 < //     /**
1332 < //      * getQueueLength reports number of waiting threads
1333 < //      */
1334 < //     public void testGetQueueLength()      { testGetQueueLength(false); }
1335 < //     public void testGetQueueLength_fair() { testGetQueueLength(true); }
1336 < //     public void testGetQueueLength(boolean fair) {
1337 < //         final PublicReentrantReadWriteLock lock =
1338 < //             new PublicReentrantReadWriteLock(fair);
1339 < //         Thread t1 = new Thread(new InterruptedLockRunnable(lock));
1340 < //         Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
1341 < //         assertEquals(0, lock.getQueueLength());
1342 < //         lock.writeLock().lock();
1343 < //         t1.start();
1344 < //         waitForQueuedThread(lock, t1);
1345 < //         assertEquals(1, lock.getQueueLength());
1346 < //         t2.start();
1347 < //         waitForQueuedThread(lock, t2);
1348 < //         assertEquals(2, lock.getQueueLength());
1349 < //         t1.interrupt();
1350 < //         awaitTermination(t1);
1351 < //         assertEquals(1, lock.getQueueLength());
1352 < //         lock.writeLock().unlock();
1353 < //         awaitTermination(t2);
1354 < //         assertEquals(0, lock.getQueueLength());
1355 < //     }
1356 <
1357 < //     /**
1358 < //      * getQueuedThreads includes waiting threads
1359 < //      */
1360 < //     public void testGetQueuedThreads()      { testGetQueuedThreads(false); }
1361 < //     public void testGetQueuedThreads_fair() { testGetQueuedThreads(true); }
1362 < //     public void testGetQueuedThreads(boolean fair) {
1363 < //         final PublicReentrantReadWriteLock lock =
1364 < //             new PublicReentrantReadWriteLock(fair);
1365 < //         Thread t1 = new Thread(new InterruptedLockRunnable(lock));
1366 < //         Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
1367 < //         assertTrue(lock.getQueuedThreads().isEmpty());
1368 < //         lock.writeLock().lock();
1369 < //         assertTrue(lock.getQueuedThreads().isEmpty());
1370 < //         t1.start();
1371 < //         waitForQueuedThread(lock, t1);
1372 < //         assertEquals(1, lock.getQueuedThreads().size());
1373 < //         assertTrue(lock.getQueuedThreads().contains(t1));
1374 < //         t2.start();
1375 < //         waitForQueuedThread(lock, t2);
1376 < //         assertEquals(2, lock.getQueuedThreads().size());
1377 < //         assertTrue(lock.getQueuedThreads().contains(t1));
1378 < //         assertTrue(lock.getQueuedThreads().contains(t2));
1379 < //         t1.interrupt();
1380 < //         awaitTermination(t1);
1381 < //         assertFalse(lock.getQueuedThreads().contains(t1));
1382 < //         assertTrue(lock.getQueuedThreads().contains(t2));
1383 < //         assertEquals(1, lock.getQueuedThreads().size());
1384 < //         lock.writeLock().unlock();
1385 < //         awaitTermination(t2);
1386 < //         assertTrue(lock.getQueuedThreads().isEmpty());
1387 < //     }
1388 <
1389 < //     /**
1390 < //      * hasWaiters throws NPE if null
1391 < //      */
1392 < //     public void testHasWaitersNPE()      { testHasWaitersNPE(false); }
1393 < //     public void testHasWaitersNPE_fair() { testHasWaitersNPE(true); }
1394 < //     public void testHasWaitersNPE(boolean fair) {
1395 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1396 < //         try {
1397 < //             lock.hasWaiters(null);
1398 < //             shouldThrow();
1399 < //         } catch (NullPointerException success) {}
1400 < //     }
1401 <
1402 < //     /**
1403 < //      * getWaitQueueLength throws NPE if null
1404 < //      */
1405 < //     public void testGetWaitQueueLengthNPE()      { testGetWaitQueueLengthNPE(false); }
1406 < //     public void testGetWaitQueueLengthNPE_fair() { testGetWaitQueueLengthNPE(true); }
1407 < //     public void testGetWaitQueueLengthNPE(boolean fair) {
1408 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1409 < //         try {
1410 < //             lock.getWaitQueueLength(null);
1411 < //             shouldThrow();
1412 < //         } catch (NullPointerException success) {}
1413 < //     }
1414 <
1415 < //     /**
1416 < //      * getWaitingThreads throws NPE if null
1417 < //      */
1418 < //     public void testGetWaitingThreadsNPE()      { testGetWaitingThreadsNPE(false); }
1419 < //     public void testGetWaitingThreadsNPE_fair() { testGetWaitingThreadsNPE(true); }
1420 < //     public void testGetWaitingThreadsNPE(boolean fair) {
1421 < //         final PublicReentrantReadWriteLock lock = new PublicReentrantReadWriteLock(fair);
1422 < //         try {
1423 < //             lock.getWaitingThreads(null);
1424 < //             shouldThrow();
1425 < //         } catch (NullPointerException success) {}
1426 < //     }
1427 <
1428 < //     /**
1429 < //      * hasWaiters throws IllegalArgumentException if not owned
1430 < //      */
1431 < //     public void testHasWaitersIAE()      { testHasWaitersIAE(false); }
1432 < //     public void testHasWaitersIAE_fair() { testHasWaitersIAE(true); }
1433 < //     public void testHasWaitersIAE(boolean fair) {
1434 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1435 < //         final Condition c = lock.writeLock().newCondition();
1436 < //         final ReentrantReadWriteLock lock2 = new ReentrantReadWriteLock(fair);
1437 < //         try {
1438 < //             lock2.hasWaiters(c);
1439 < //             shouldThrow();
1440 < //         } catch (IllegalArgumentException success) {}
1441 < //     }
1442 <
1443 < //     /**
1444 < //      * hasWaiters throws IllegalMonitorStateException if not locked
1445 < //      */
1446 < //     public void testHasWaitersIMSE()      { testHasWaitersIMSE(false); }
1447 < //     public void testHasWaitersIMSE_fair() { testHasWaitersIMSE(true); }
1448 < //     public void testHasWaitersIMSE(boolean fair) {
1449 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1450 < //         final Condition c = lock.writeLock().newCondition();
1451 < //         try {
1452 < //             lock.hasWaiters(c);
1453 < //             shouldThrow();
1454 < //         } catch (IllegalMonitorStateException success) {}
1455 < //     }
1456 <
1457 < //     /**
1458 < //      * getWaitQueueLength throws IllegalArgumentException if not owned
1459 < //      */
1460 < //     public void testGetWaitQueueLengthIAE()      { testGetWaitQueueLengthIAE(false); }
1461 < //     public void testGetWaitQueueLengthIAE_fair() { testGetWaitQueueLengthIAE(true); }
1462 < //     public void testGetWaitQueueLengthIAE(boolean fair) {
1463 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1464 < //         final Condition c = lock.writeLock().newCondition();
1465 < //         final ReentrantReadWriteLock lock2 = new ReentrantReadWriteLock(fair);
1466 < //         try {
1467 < //             lock2.getWaitQueueLength(c);
1468 < //             shouldThrow();
1469 < //         } catch (IllegalArgumentException success) {}
1470 < //     }
1471 <
1472 < //     /**
1473 < //      * getWaitQueueLength throws IllegalMonitorStateException if not locked
1474 < //      */
1475 < //     public void testGetWaitQueueLengthIMSE()      { testGetWaitQueueLengthIMSE(false); }
1476 < //     public void testGetWaitQueueLengthIMSE_fair() { testGetWaitQueueLengthIMSE(true); }
1477 < //     public void testGetWaitQueueLengthIMSE(boolean fair) {
1478 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1479 < //         final Condition c = lock.writeLock().newCondition();
1480 < //         try {
1481 < //             lock.getWaitQueueLength(c);
1482 < //             shouldThrow();
1483 < //         } catch (IllegalMonitorStateException success) {}
1484 < //     }
1485 <
1486 < //     /**
1487 < //      * getWaitingThreads throws IllegalArgumentException if not owned
1488 < //      */
1489 < //     public void testGetWaitingThreadsIAE()      { testGetWaitingThreadsIAE(false); }
1490 < //     public void testGetWaitingThreadsIAE_fair() { testGetWaitingThreadsIAE(true); }
1491 < //     public void testGetWaitingThreadsIAE(boolean fair) {
1492 < //         final PublicReentrantReadWriteLock lock =
1493 < //             new PublicReentrantReadWriteLock(fair);
1494 < //         final Condition c = lock.writeLock().newCondition();
1495 < //         final PublicReentrantReadWriteLock lock2 =
1496 < //             new PublicReentrantReadWriteLock(fair);
1497 < //         try {
1498 < //             lock2.getWaitingThreads(c);
1499 < //             shouldThrow();
1500 < //         } catch (IllegalArgumentException success) {}
1501 < //     }
1502 <
1503 < //     /**
1504 < //      * getWaitingThreads throws IllegalMonitorStateException if not locked
1505 < //      */
1506 < //     public void testGetWaitingThreadsIMSE()      { testGetWaitingThreadsIMSE(false); }
1507 < //     public void testGetWaitingThreadsIMSE_fair() { testGetWaitingThreadsIMSE(true); }
1508 < //     public void testGetWaitingThreadsIMSE(boolean fair) {
1509 < //         final PublicReentrantReadWriteLock lock =
1510 < //             new PublicReentrantReadWriteLock(fair);
1511 < //         final Condition c = lock.writeLock().newCondition();
1512 < //         try {
1513 < //             lock.getWaitingThreads(c);
1514 < //             shouldThrow();
1515 < //         } catch (IllegalMonitorStateException success) {}
1516 < //     }
1517 <
1518 < //     /**
1519 < //      * hasWaiters returns true when a thread is waiting, else false
1520 < //      */
1521 < //     public void testHasWaiters()      { testHasWaiters(false); }
1522 < //     public void testHasWaiters_fair() { testHasWaiters(true); }
1523 < //     public void testHasWaiters(boolean fair) {
1524 < //         final PublicReentrantReadWriteLock lock =
1525 < //             new PublicReentrantReadWriteLock(fair);
1526 < //         final Condition c = lock.writeLock().newCondition();
1527 < //         final CountDownLatch locked = new CountDownLatch(1);
1528 < //         Thread t = newStartedThread(new CheckedRunnable() {
1529 < //             public void realRun() throws InterruptedException {
1530 < //                 lock.writeLock().lock();
1531 < //                 assertHasNoWaiters(lock, c);
1532 < //                 assertFalse(lock.hasWaiters(c));
1533 < //                 locked.countDown();
1534 < //                 c.await();
1535 < //                 assertHasNoWaiters(lock, c);
1536 < //                 assertFalse(lock.hasWaiters(c));
1537 < //                 lock.writeLock().unlock();
1538 < //             }});
1539 <
1540 < //         await(locked);
1541 < //         lock.writeLock().lock();
1542 < //         assertHasWaiters(lock, c, t);
1543 < //         assertTrue(lock.hasWaiters(c));
1544 < //         c.signal();
1545 < //         assertHasNoWaiters(lock, c);
1546 < //         assertFalse(lock.hasWaiters(c));
1547 < //         lock.writeLock().unlock();
1548 < //         awaitTermination(t);
1549 < //         assertHasNoWaiters(lock, c);
1550 < //     }
1551 <
1552 < //     /**
1553 < //      * getWaitQueueLength returns number of waiting threads
1554 < //      */
1555 < //     public void testGetWaitQueueLength()      { testGetWaitQueueLength(false); }
1556 < //     public void testGetWaitQueueLength_fair() { testGetWaitQueueLength(true); }
1557 < //     public void testGetWaitQueueLength(boolean fair) {
1558 < //         final PublicReentrantReadWriteLock lock =
1559 < //             new PublicReentrantReadWriteLock(fair);
1560 < //         final Condition c = lock.writeLock().newCondition();
1561 < //         final CountDownLatch locked = new CountDownLatch(1);
1562 < //         Thread t = newStartedThread(new CheckedRunnable() {
1563 < //             public void realRun() throws InterruptedException {
1564 < //                 lock.writeLock().lock();
1565 < //                 assertEquals(0, lock.getWaitQueueLength(c));
1566 < //                 locked.countDown();
1567 < //                 c.await();
1568 < //                 lock.writeLock().unlock();
1569 < //             }});
1570 <
1571 < //         await(locked);
1572 < //         lock.writeLock().lock();
1573 < //         assertHasWaiters(lock, c, t);
1574 < //         assertEquals(1, lock.getWaitQueueLength(c));
1575 < //         c.signal();
1576 < //         assertHasNoWaiters(lock, c);
1577 < //         assertEquals(0, lock.getWaitQueueLength(c));
1578 < //         lock.writeLock().unlock();
1579 < //         awaitTermination(t);
1580 < //     }
1581 <
1582 < //     /**
1583 < //      * getWaitingThreads returns only and all waiting threads
1584 < //      */
1585 < //     public void testGetWaitingThreads()      { testGetWaitingThreads(false); }
1586 < //     public void testGetWaitingThreads_fair() { testGetWaitingThreads(true); }
1587 < //     public void testGetWaitingThreads(boolean fair) {
1588 < //         final PublicReentrantReadWriteLock lock =
1589 < //             new PublicReentrantReadWriteLock(fair);
1590 < //         final Condition c = lock.writeLock().newCondition();
1591 < //         final CountDownLatch locked1 = new CountDownLatch(1);
1592 < //         final CountDownLatch locked2 = new CountDownLatch(1);
1593 < //         Thread t1 = new Thread(new CheckedRunnable() {
1594 < //             public void realRun() throws InterruptedException {
1595 < //                 lock.writeLock().lock();
1596 < //                 assertTrue(lock.getWaitingThreads(c).isEmpty());
1597 < //                 locked1.countDown();
1598 < //                 c.await();
1599 < //                 lock.writeLock().unlock();
1600 < //             }});
1601 <
1602 < //         Thread t2 = new Thread(new CheckedRunnable() {
1603 < //             public void realRun() throws InterruptedException {
1604 < //                 lock.writeLock().lock();
1605 < //                 assertFalse(lock.getWaitingThreads(c).isEmpty());
1606 < //                 locked2.countDown();
1607 < //                 c.await();
1608 < //                 lock.writeLock().unlock();
1609 < //             }});
1610 <
1611 < //         lock.writeLock().lock();
1612 < //         assertTrue(lock.getWaitingThreads(c).isEmpty());
1613 < //         lock.writeLock().unlock();
1614 <
1615 < //         t1.start();
1616 < //         await(locked1);
1617 < //         t2.start();
1618 < //         await(locked2);
1619 <
1620 < //         lock.writeLock().lock();
1621 < //         assertTrue(lock.hasWaiters(c));
1622 < //         assertTrue(lock.getWaitingThreads(c).contains(t1));
1623 < //         assertTrue(lock.getWaitingThreads(c).contains(t2));
1624 < //         assertEquals(2, lock.getWaitingThreads(c).size());
1625 < //         c.signalAll();
1626 < //         assertHasNoWaiters(lock, c);
1627 < //         lock.writeLock().unlock();
1628 <
1629 < //         awaitTermination(t1);
1630 < //         awaitTermination(t2);
1631 <
1632 < //         assertHasNoWaiters(lock, c);
1633 < //     }
1634 <
1635 < //     /**
1636 < //      * toString indicates current lock state
1637 < //      */
1638 < //     public void testToString()      { testToString(false); }
1639 < //     public void testToString_fair() { testToString(true); }
1640 < //     public void testToString(boolean fair) {
1641 < //         ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1642 < //         assertTrue(lock.toString().contains("Write locks = 0"));
1643 < //         assertTrue(lock.toString().contains("Read locks = 0"));
1644 < //         lock.writeLock().lock();
1645 < //         assertTrue(lock.toString().contains("Write locks = 1"));
1646 < //         assertTrue(lock.toString().contains("Read locks = 0"));
1647 < //         lock.writeLock().unlock();
1648 < //         lock.readLock().lock();
1649 < //         lock.readLock().lock();
1650 < //         assertTrue(lock.toString().contains("Write locks = 0"));
1651 < //         assertTrue(lock.toString().contains("Read locks = 2"));
1652 < //     }
1653 <
1654 < //     /**
1655 < //      * readLock.toString indicates current lock state
1656 < //      */
1657 < //     public void testReadLockToString()      { testReadLockToString(false); }
1658 < //     public void testReadLockToString_fair() { testReadLockToString(true); }
1659 < //     public void testReadLockToString(boolean fair) {
1660 < //         ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1661 < //         assertTrue(lock.readLock().toString().contains("Read locks = 0"));
1662 < //         lock.readLock().lock();
1663 < //         lock.readLock().lock();
1664 < //         assertTrue(lock.readLock().toString().contains("Read locks = 2"));
1665 < //     }
1666 <
1667 < //     /**
1668 < //      * writeLock.toString indicates current lock state
1669 < //      */
1670 < //     public void testWriteLockToString()      { testWriteLockToString(false); }
1671 < //     public void testWriteLockToString_fair() { testWriteLockToString(true); }
1672 < //     public void testWriteLockToString(boolean fair) {
1673 < //         ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1674 < //         assertTrue(lock.writeLock().toString().contains("Unlocked"));
1675 < //         lock.writeLock().lock();
1676 < //         assertTrue(lock.writeLock().toString().contains("Locked"));
1677 < //         lock.writeLock().unlock();
1678 < //         assertTrue(lock.writeLock().toString().contains("Unlocked"));
1679 < //     }
513 >    /**
514 >     * writeLock() succeeds only after reading threads unlock
515 >     */
516 >    public void testWriteAfterMultipleReadLocks() {
517 >        final StampedLock lock = new StampedLock();
518 >        long s = lock.readLock();
519 >        Thread t1 = newStartedThread(new CheckedRunnable() {
520 >            public void realRun() {
521 >                long rs = lock.readLock();
522 >                lock.unlockRead(rs);
523 >            }});
524 >
525 >        awaitTermination(t1);
526 >
527 >        Thread t2 = newStartedThread(new CheckedRunnable() {
528 >            public void realRun() {
529 >                long ws = lock.writeLock();
530 >                lock.unlockWrite(ws);
531 >            }});
532 >
533 >        assertTrue(lock.isReadLocked());
534 >        assertFalse(lock.isWriteLocked());
535 >        lock.unlockRead(s);
536 >        awaitTermination(t2);
537 >        assertUnlocked(lock);
538 >    }
539 >
540 >    /**
541 >     * readLock() succeed only after a writing thread unlocks
542 >     */
543 >    public void testReadAfterWriteLock() {
544 >        final StampedLock lock = new StampedLock();
545 >        final CountDownLatch threadsStarted = new CountDownLatch(2);
546 >        final long s = lock.writeLock();
547 >        final Runnable acquireReleaseReadLock = new CheckedRunnable() {
548 >            public void realRun() {
549 >                threadsStarted.countDown();
550 >                long rs = lock.readLock();
551 >                assertTrue(lock.isReadLocked());
552 >                assertFalse(lock.isWriteLocked());
553 >                lock.unlockRead(rs);
554 >            }};
555 >        Thread t1 = newStartedThread(acquireReleaseReadLock);
556 >        Thread t2 = newStartedThread(acquireReleaseReadLock);
557 >
558 >        await(threadsStarted);
559 >        assertThreadBlocks(t1, Thread.State.WAITING);
560 >        assertThreadBlocks(t2, Thread.State.WAITING);
561 >        assertTrue(lock.isWriteLocked());
562 >        assertFalse(lock.isReadLocked());
563 >        releaseWriteLock(lock, s);
564 >        awaitTermination(t1);
565 >        awaitTermination(t2);
566 >        assertUnlocked(lock);
567 >    }
568 >
569 >    /**
570 >     * tryReadLock succeeds if read locked but not write locked
571 >     */
572 >    public void testTryLockWhenReadLocked() {
573 >        final StampedLock lock = new StampedLock();
574 >        long s = lock.readLock();
575 >        Thread t = newStartedThread(new CheckedRunnable() {
576 >            public void realRun() {
577 >                long rs = lock.tryReadLock();
578 >                assertValid(lock, rs);
579 >                lock.unlockRead(rs);
580 >            }});
581 >
582 >        awaitTermination(t);
583 >        lock.unlockRead(s);
584 >    }
585 >
586 >    /**
587 >     * tryWriteLock fails when read locked
588 >     */
589 >    public void testTryWriteLockWhenReadLocked() {
590 >        final StampedLock lock = new StampedLock();
591 >        long s = lock.readLock();
592 >        Thread t = newStartedThread(new CheckedRunnable() {
593 >            public void realRun() {
594 >                assertEquals(0L, lock.tryWriteLock());
595 >            }});
596 >
597 >        awaitTermination(t);
598 >        lock.unlockRead(s);
599 >    }
600 >
601 >    /**
602 >     * timed lock operations time out if lock not available
603 >     */
604 >    public void testTimedLock_Timeout() throws Exception {
605 >        ArrayList<Future<?>> futures = new ArrayList<>();
606 >
607 >        // Write locked
608 >        final StampedLock lock = new StampedLock();
609 >        long stamp = lock.writeLock();
610 >        assertEquals(0L, lock.tryReadLock(0L, DAYS));
611 >        assertEquals(0L, lock.tryReadLock(Long.MIN_VALUE, DAYS));
612 >        assertFalse(lock.asReadLock().tryLock(0L, DAYS));
613 >        assertFalse(lock.asReadLock().tryLock(Long.MIN_VALUE, DAYS));
614 >        assertEquals(0L, lock.tryWriteLock(0L, DAYS));
615 >        assertEquals(0L, lock.tryWriteLock(Long.MIN_VALUE, DAYS));
616 >        assertFalse(lock.asWriteLock().tryLock(0L, DAYS));
617 >        assertFalse(lock.asWriteLock().tryLock(Long.MIN_VALUE, DAYS));
618 >
619 >        futures.add(cachedThreadPool.submit(new CheckedRunnable() {
620 >            public void realRun() throws InterruptedException {
621 >                long startTime = System.nanoTime();
622 >                assertEquals(0L, lock.tryWriteLock(timeoutMillis(), MILLISECONDS));
623 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
624 >            }}));
625 >
626 >        futures.add(cachedThreadPool.submit(new CheckedRunnable() {
627 >            public void realRun() throws InterruptedException {
628 >                long startTime = System.nanoTime();
629 >                assertEquals(0L, lock.tryReadLock(timeoutMillis(), MILLISECONDS));
630 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
631 >            }}));
632 >
633 >        // Read locked
634 >        final StampedLock lock2 = new StampedLock();
635 >        long stamp2 = lock2.readLock();
636 >        assertEquals(0L, lock2.tryWriteLock(0L, DAYS));
637 >        assertEquals(0L, lock2.tryWriteLock(Long.MIN_VALUE, DAYS));
638 >        assertFalse(lock2.asWriteLock().tryLock(0L, DAYS));
639 >        assertFalse(lock2.asWriteLock().tryLock(Long.MIN_VALUE, DAYS));
640 >
641 >        futures.add(cachedThreadPool.submit(new CheckedRunnable() {
642 >            public void realRun() throws InterruptedException {
643 >                long startTime = System.nanoTime();
644 >                assertEquals(0L, lock2.tryWriteLock(timeoutMillis(), MILLISECONDS));
645 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
646 >            }}));
647 >
648 >        for (Future<?> future : futures)
649 >            assertNull(future.get());
650 >
651 >        releaseWriteLock(lock, stamp);
652 >        releaseReadLock(lock2, stamp2);
653 >    }
654 >
655 >    /**
656 >     * writeLockInterruptibly succeeds if unlocked
657 >     */
658 >    public void testWriteLockInterruptibly() throws InterruptedException {
659 >        final StampedLock lock = new StampedLock();
660 >        long s = lock.writeLockInterruptibly();
661 >        assertTrue(lock.isWriteLocked());
662 >        releaseWriteLock(lock, s);
663 >    }
664 >
665 >    /**
666 >     * readLockInterruptibly succeeds if lock free
667 >     */
668 >    public void testReadLockInterruptibly() throws InterruptedException {
669 >        final StampedLock lock = new StampedLock();
670 >
671 >        long s = assertValid(lock, lock.readLockInterruptibly());
672 >        assertTrue(lock.isReadLocked());
673 >        lock.unlockRead(s);
674 >
675 >        lock.asReadLock().lockInterruptibly();
676 >        assertTrue(lock.isReadLocked());
677 >        lock.asReadLock().unlock();
678 >    }
679 >
680 >    /**
681 >     * A serialized lock deserializes as unlocked
682 >     */
683 >    public void testSerialization() {
684 >        StampedLock lock = new StampedLock();
685 >        lock.writeLock();
686 >        StampedLock clone = serialClone(lock);
687 >        assertTrue(lock.isWriteLocked());
688 >        assertFalse(clone.isWriteLocked());
689 >        long s = clone.writeLock();
690 >        assertTrue(clone.isWriteLocked());
691 >        clone.unlockWrite(s);
692 >        assertFalse(clone.isWriteLocked());
693 >    }
694 >
695 >    /**
696 >     * toString indicates current lock state
697 >     */
698 >    public void testToString() {
699 >        StampedLock lock = new StampedLock();
700 >        assertTrue(lock.toString().contains("Unlocked"));
701 >        long s = lock.writeLock();
702 >        assertTrue(lock.toString().contains("Write-locked"));
703 >        lock.unlockWrite(s);
704 >        s = lock.readLock();
705 >        assertTrue(lock.toString().contains("Read-locks"));
706 >        releaseReadLock(lock, s);
707 >    }
708 >
709 >    /**
710 >     * tryOptimisticRead succeeds and validates if unlocked, fails if
711 >     * exclusively locked
712 >     */
713 >    public void testValidateOptimistic() throws InterruptedException {
714 >        StampedLock lock = new StampedLock();
715 >
716 >        assertValid(lock, lock.tryOptimisticRead());
717 >
718 >        for (Function<StampedLock, Long> writeLocker : writeLockers()) {
719 >            long s = assertValid(lock, writeLocker.apply(lock));
720 >            assertEquals(0L, lock.tryOptimisticRead());
721 >            releaseWriteLock(lock, s);
722 >        }
723 >
724 >        for (Function<StampedLock, Long> readLocker : readLockers()) {
725 >            long s = assertValid(lock, readLocker.apply(lock));
726 >            long p = assertValid(lock, lock.tryOptimisticRead());
727 >            releaseReadLock(lock, s);
728 >            assertTrue(lock.validate(p));
729 >        }
730 >
731 >        assertValid(lock, lock.tryOptimisticRead());
732 >    }
733 >
734 >    /**
735 >     * tryOptimisticRead stamp does not validate if a write lock intervenes
736 >     */
737 >    public void testValidateOptimisticWriteLocked() {
738 >        final StampedLock lock = new StampedLock();
739 >        final long p = assertValid(lock, lock.tryOptimisticRead());
740 >        final long s = assertValid(lock, lock.writeLock());
741 >        assertFalse(lock.validate(p));
742 >        assertEquals(0L, lock.tryOptimisticRead());
743 >        assertTrue(lock.validate(s));
744 >        lock.unlockWrite(s);
745 >    }
746 >
747 >    /**
748 >     * tryOptimisticRead stamp does not validate if a write lock
749 >     * intervenes in another thread
750 >     */
751 >    public void testValidateOptimisticWriteLocked2()
752 >            throws InterruptedException {
753 >        final CountDownLatch locked = new CountDownLatch(1);
754 >        final StampedLock lock = new StampedLock();
755 >        final long p = assertValid(lock, lock.tryOptimisticRead());
756 >
757 >        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
758 >            public void realRun() throws InterruptedException {
759 >                lock.writeLockInterruptibly();
760 >                locked.countDown();
761 >                lock.writeLockInterruptibly();
762 >            }});
763 >
764 >        await(locked);
765 >        assertFalse(lock.validate(p));
766 >        assertEquals(0L, lock.tryOptimisticRead());
767 >        assertThreadBlocks(t, Thread.State.WAITING);
768 >        t.interrupt();
769 >        awaitTermination(t);
770 >        assertTrue(lock.isWriteLocked());
771 >    }
772 >
773 >    /**
774 >     * tryConvertToOptimisticRead succeeds and validates if successfully locked
775 >     */
776 >    public void testTryConvertToOptimisticRead() throws InterruptedException {
777 >        StampedLock lock = new StampedLock();
778 >        long s, p, q;
779 >        assertEquals(0L, lock.tryConvertToOptimisticRead(0L));
780 >
781 >        s = assertValid(lock, lock.tryOptimisticRead());
782 >        assertEquals(s, lock.tryConvertToOptimisticRead(s));
783 >        assertTrue(lock.validate(s));
784 >
785 >        for (Function<StampedLock, Long> writeLocker : writeLockers()) {
786 >            s = assertValid(lock, writeLocker.apply(lock));
787 >            p = assertValid(lock, lock.tryConvertToOptimisticRead(s));
788 >            assertFalse(lock.validate(s));
789 >            assertTrue(lock.validate(p));
790 >            assertUnlocked(lock);
791 >        }
792 >
793 >        for (Function<StampedLock, Long> readLocker : readLockers()) {
794 >            s = assertValid(lock, readLocker.apply(lock));
795 >            q = assertValid(lock, lock.tryOptimisticRead());
796 >            assertEquals(q, lock.tryConvertToOptimisticRead(q));
797 >            assertTrue(lock.validate(q));
798 >            assertTrue(lock.isReadLocked());
799 >            p = assertValid(lock, lock.tryConvertToOptimisticRead(s));
800 >            assertTrue(lock.validate(p));
801 >            assertTrue(lock.validate(s));
802 >            assertUnlocked(lock);
803 >            assertEquals(q, lock.tryConvertToOptimisticRead(q));
804 >            assertTrue(lock.validate(q));
805 >        }
806 >    }
807 >
808 >    /**
809 >     * tryConvertToReadLock succeeds for valid stamps
810 >     */
811 >    public void testTryConvertToReadLock() throws InterruptedException {
812 >        StampedLock lock = new StampedLock();
813 >        long s, p;
814 >
815 >        assertEquals(0L, lock.tryConvertToReadLock(0L));
816 >
817 >        s = assertValid(lock, lock.tryOptimisticRead());
818 >        p = assertValid(lock, lock.tryConvertToReadLock(s));
819 >        assertTrue(lock.isReadLocked());
820 >        assertEquals(1, lock.getReadLockCount());
821 >        assertTrue(lock.validate(s));
822 >        lock.unlockRead(p);
823 >
824 >        s = assertValid(lock, lock.tryOptimisticRead());
825 >        lock.readLock();
826 >        p = assertValid(lock, lock.tryConvertToReadLock(s));
827 >        assertTrue(lock.isReadLocked());
828 >        assertEquals(2, lock.getReadLockCount());
829 >        lock.unlockRead(p);
830 >        lock.unlockRead(p);
831 >        assertUnlocked(lock);
832 >
833 >        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
834 >            for (Function<StampedLock, Long> writeLocker : writeLockers()) {
835 >                s = assertValid(lock, writeLocker.apply(lock));
836 >                p = assertValid(lock, lock.tryConvertToReadLock(s));
837 >                assertFalse(lock.validate(s));
838 >                assertTrue(lock.isReadLocked());
839 >                assertEquals(1, lock.getReadLockCount());
840 >                readUnlocker.accept(lock, p);
841 >            }
842 >
843 >            for (Function<StampedLock, Long> readLocker : readLockers()) {
844 >                s = assertValid(lock, readLocker.apply(lock));
845 >                assertEquals(s, lock.tryConvertToReadLock(s));
846 >                assertTrue(lock.validate(s));
847 >                assertTrue(lock.isReadLocked());
848 >                assertEquals(1, lock.getReadLockCount());
849 >                readUnlocker.accept(lock, s);
850 >            }
851 >        }
852 >    }
853 >
854 >    /**
855 >     * tryConvertToWriteLock succeeds if lock available; fails if multiply read locked
856 >     */
857 >    public void testTryConvertToWriteLock() throws InterruptedException {
858 >        StampedLock lock = new StampedLock();
859 >        long s, p;
860 >
861 >        assertEquals(0L, lock.tryConvertToWriteLock(0L));
862 >
863 >        assertTrue((s = lock.tryOptimisticRead()) != 0L);
864 >        assertTrue((p = lock.tryConvertToWriteLock(s)) != 0L);
865 >        assertTrue(lock.isWriteLocked());
866 >        lock.unlockWrite(p);
867 >
868 >        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
869 >            for (Function<StampedLock, Long> writeLocker : writeLockers()) {
870 >                s = assertValid(lock, writeLocker.apply(lock));
871 >                assertEquals(s, lock.tryConvertToWriteLock(s));
872 >                assertTrue(lock.validate(s));
873 >                assertTrue(lock.isWriteLocked());
874 >                writeUnlocker.accept(lock, s);
875 >            }
876 >
877 >            for (Function<StampedLock, Long> readLocker : readLockers()) {
878 >                s = assertValid(lock, readLocker.apply(lock));
879 >                p = assertValid(lock, lock.tryConvertToWriteLock(s));
880 >                assertFalse(lock.validate(s));
881 >                assertTrue(lock.validate(p));
882 >                assertTrue(lock.isWriteLocked());
883 >                writeUnlocker.accept(lock, p);
884 >            }
885 >        }
886 >
887 >        // failure if multiply read locked
888 >        for (Function<StampedLock, Long> readLocker : readLockers()) {
889 >            s = assertValid(lock, readLocker.apply(lock));
890 >            p = assertValid(lock, readLocker.apply(lock));
891 >            assertEquals(0L, lock.tryConvertToWriteLock(s));
892 >            assertTrue(lock.validate(s));
893 >            assertTrue(lock.validate(p));
894 >            assertEquals(2, lock.getReadLockCount());
895 >            lock.unlock(p);
896 >            lock.unlock(s);
897 >            assertUnlocked(lock);
898 >        }
899 >    }
900 >
901 >    /**
902 >     * asWriteLock can be locked and unlocked
903 >     */
904 >    public void testAsWriteLock() throws Throwable {
905 >        StampedLock sl = new StampedLock();
906 >        Lock lock = sl.asWriteLock();
907 >        for (Action locker : lockLockers(lock)) {
908 >            locker.run();
909 >            assertTrue(sl.isWriteLocked());
910 >            assertFalse(sl.isReadLocked());
911 >            assertFalse(lock.tryLock());
912 >            lock.unlock();
913 >            assertUnlocked(sl);
914 >        }
915 >    }
916 >
917 >    /**
918 >     * asReadLock can be locked and unlocked
919 >     */
920 >    public void testAsReadLock() throws Throwable {
921 >        StampedLock sl = new StampedLock();
922 >        Lock lock = sl.asReadLock();
923 >        for (Action locker : lockLockers(lock)) {
924 >            locker.run();
925 >            assertTrue(sl.isReadLocked());
926 >            assertFalse(sl.isWriteLocked());
927 >            assertEquals(1, sl.getReadLockCount());
928 >            locker.run();
929 >            assertTrue(sl.isReadLocked());
930 >            assertEquals(2, sl.getReadLockCount());
931 >            lock.unlock();
932 >            lock.unlock();
933 >            assertUnlocked(sl);
934 >        }
935 >    }
936 >
937 >    /**
938 >     * asReadWriteLock.writeLock can be locked and unlocked
939 >     */
940 >    public void testAsReadWriteLockWriteLock() throws Throwable {
941 >        StampedLock sl = new StampedLock();
942 >        Lock lock = sl.asReadWriteLock().writeLock();
943 >        for (Action locker : lockLockers(lock)) {
944 >            locker.run();
945 >            assertTrue(sl.isWriteLocked());
946 >            assertFalse(sl.isReadLocked());
947 >            assertFalse(lock.tryLock());
948 >            lock.unlock();
949 >            assertUnlocked(sl);
950 >        }
951 >    }
952 >
953 >    /**
954 >     * asReadWriteLock.readLock can be locked and unlocked
955 >     */
956 >    public void testAsReadWriteLockReadLock() throws Throwable {
957 >        StampedLock sl = new StampedLock();
958 >        Lock lock = sl.asReadWriteLock().readLock();
959 >        for (Action locker : lockLockers(lock)) {
960 >            locker.run();
961 >            assertTrue(sl.isReadLocked());
962 >            assertFalse(sl.isWriteLocked());
963 >            assertEquals(1, sl.getReadLockCount());
964 >            locker.run();
965 >            assertTrue(sl.isReadLocked());
966 >            assertEquals(2, sl.getReadLockCount());
967 >            lock.unlock();
968 >            lock.unlock();
969 >            assertUnlocked(sl);
970 >        }
971 >    }
972 >
973 >    /**
974 >     * Lock.newCondition throws UnsupportedOperationException
975 >     */
976 >    public void testLockViewsDoNotSupportConditions() {
977 >        StampedLock sl = new StampedLock();
978 >        assertThrows(UnsupportedOperationException.class,
979 >                     () -> sl.asWriteLock().newCondition(),
980 >                     () -> sl.asReadLock().newCondition(),
981 >                     () -> sl.asReadWriteLock().writeLock().newCondition(),
982 >                     () -> sl.asReadWriteLock().readLock().newCondition());
983 >    }
984 >
985 >    /**
986 >     * Passing optimistic read stamps to unlock operations result in
987 >     * IllegalMonitorStateException
988 >     */
989 >    public void testCannotUnlockOptimisticReadStamps() {
990 >        {
991 >            StampedLock sl = new StampedLock();
992 >            long stamp = assertValid(sl, sl.tryOptimisticRead());
993 >            assertThrows(IllegalMonitorStateException.class,
994 >                () -> sl.unlockRead(stamp));
995 >        }
996 >        {
997 >            StampedLock sl = new StampedLock();
998 >            long stamp = sl.tryOptimisticRead();
999 >            assertThrows(IllegalMonitorStateException.class,
1000 >                () -> sl.unlock(stamp));
1001 >        }
1002 >
1003 >        {
1004 >            StampedLock sl = new StampedLock();
1005 >            long stamp = sl.tryOptimisticRead();
1006 >            sl.writeLock();
1007 >            assertThrows(IllegalMonitorStateException.class,
1008 >                () -> sl.unlock(stamp));
1009 >        }
1010 >        {
1011 >            StampedLock sl = new StampedLock();
1012 >            sl.readLock();
1013 >            long stamp = assertValid(sl, sl.tryOptimisticRead());
1014 >            assertThrows(IllegalMonitorStateException.class,
1015 >                () -> sl.unlockRead(stamp));
1016 >        }
1017 >        {
1018 >            StampedLock sl = new StampedLock();
1019 >            sl.readLock();
1020 >            long stamp = assertValid(sl, sl.tryOptimisticRead());
1021 >            assertThrows(IllegalMonitorStateException.class,
1022 >                () -> sl.unlock(stamp));
1023 >        }
1024 >
1025 >        {
1026 >            StampedLock sl = new StampedLock();
1027 >            long stamp = sl.tryConvertToOptimisticRead(sl.writeLock());
1028 >            assertValid(sl, stamp);
1029 >            sl.writeLock();
1030 >            assertThrows(IllegalMonitorStateException.class,
1031 >                () -> sl.unlockWrite(stamp));
1032 >        }
1033 >        {
1034 >            StampedLock sl = new StampedLock();
1035 >            long stamp = sl.tryConvertToOptimisticRead(sl.writeLock());
1036 >            sl.writeLock();
1037 >            assertThrows(IllegalMonitorStateException.class,
1038 >                () -> sl.unlock(stamp));
1039 >        }
1040 >        {
1041 >            StampedLock sl = new StampedLock();
1042 >            long stamp = sl.tryConvertToOptimisticRead(sl.writeLock());
1043 >            sl.readLock();
1044 >            assertThrows(IllegalMonitorStateException.class,
1045 >                () -> sl.unlockRead(stamp));
1046 >        }
1047 >        {
1048 >            StampedLock sl = new StampedLock();
1049 >            long stamp = sl.tryConvertToOptimisticRead(sl.writeLock());
1050 >            sl.readLock();
1051 >            assertThrows(IllegalMonitorStateException.class,
1052 >                () -> sl.unlock(stamp));
1053 >        }
1054 >
1055 >        {
1056 >            StampedLock sl = new StampedLock();
1057 >            long stamp = sl.tryConvertToOptimisticRead(sl.readLock());
1058 >            assertValid(sl, stamp);
1059 >            sl.writeLock();
1060 >            assertThrows(IllegalMonitorStateException.class,
1061 >                () -> sl.unlockWrite(stamp));
1062 >            }
1063 >        {
1064 >            StampedLock sl = new StampedLock();
1065 >            long stamp = sl.tryConvertToOptimisticRead(sl.readLock());
1066 >            sl.writeLock();
1067 >            assertThrows(IllegalMonitorStateException.class,
1068 >                () -> sl.unlock(stamp));
1069 >        }
1070 >        {
1071 >            StampedLock sl = new StampedLock();
1072 >            long stamp = sl.tryConvertToOptimisticRead(sl.readLock());
1073 >            sl.readLock();
1074 >            assertThrows(IllegalMonitorStateException.class,
1075 >                () -> sl.unlockRead(stamp));
1076 >        }
1077 >        {
1078 >            StampedLock sl = new StampedLock();
1079 >            sl.readLock();
1080 >            long stamp = sl.tryConvertToOptimisticRead(sl.readLock());
1081 >            assertValid(sl, stamp);
1082 >            sl.readLock();
1083 >            assertThrows(IllegalMonitorStateException.class,
1084 >                () -> sl.unlockRead(stamp));
1085 >        }
1086 >        {
1087 >            StampedLock sl = new StampedLock();
1088 >            long stamp = sl.tryConvertToOptimisticRead(sl.readLock());
1089 >            sl.readLock();
1090 >            assertThrows(IllegalMonitorStateException.class,
1091 >                () -> sl.unlock(stamp));
1092 >        }
1093 >        {
1094 >            StampedLock sl = new StampedLock();
1095 >            sl.readLock();
1096 >            long stamp = sl.tryConvertToOptimisticRead(sl.readLock());
1097 >            sl.readLock();
1098 >            assertThrows(IllegalMonitorStateException.class,
1099 >                () -> sl.unlock(stamp));
1100 >        }
1101 >    }
1102 >
1103 >    static long writeLockInterruptiblyUninterrupted(StampedLock sl) {
1104 >        try { return sl.writeLockInterruptibly(); }
1105 >        catch (InterruptedException ex) { throw new AssertionError(ex); }
1106 >    }
1107 >
1108 >    static long tryWriteLockUninterrupted(StampedLock sl, long time, TimeUnit unit) {
1109 >        try { return sl.tryWriteLock(time, unit); }
1110 >        catch (InterruptedException ex) { throw new AssertionError(ex); }
1111 >    }
1112 >
1113 >    static long readLockInterruptiblyUninterrupted(StampedLock sl) {
1114 >        try { return sl.readLockInterruptibly(); }
1115 >        catch (InterruptedException ex) { throw new AssertionError(ex); }
1116 >    }
1117 >
1118 >    static long tryReadLockUninterrupted(StampedLock sl, long time, TimeUnit unit) {
1119 >        try { return sl.tryReadLock(time, unit); }
1120 >        catch (InterruptedException ex) { throw new AssertionError(ex); }
1121 >    }
1122 >
1123 >    /**
1124 >     * Invalid stamps result in IllegalMonitorStateException
1125 >     */
1126 >    public void testInvalidStampsThrowIllegalMonitorStateException() {
1127 >        final StampedLock sl = new StampedLock();
1128 >
1129 >        assertThrows(IllegalMonitorStateException.class,
1130 >                     () -> sl.unlockWrite(0L),
1131 >                     () -> sl.unlockRead(0L),
1132 >                     () -> sl.unlock(0L));
1133 >
1134 >        final long optimisticStamp = sl.tryOptimisticRead();
1135 >        final long readStamp = sl.readLock();
1136 >        sl.unlockRead(readStamp);
1137 >        final long writeStamp = sl.writeLock();
1138 >        sl.unlockWrite(writeStamp);
1139 >        assertTrue(optimisticStamp != 0L && readStamp != 0L && writeStamp != 0L);
1140 >        final long[] noLongerValidStamps = { optimisticStamp, readStamp, writeStamp };
1141 >        final Runnable assertNoLongerValidStampsThrow = () -> {
1142 >            for (long noLongerValidStamp : noLongerValidStamps)
1143 >                assertThrows(IllegalMonitorStateException.class,
1144 >                             () -> sl.unlockWrite(noLongerValidStamp),
1145 >                             () -> sl.unlockRead(noLongerValidStamp),
1146 >                             () -> sl.unlock(noLongerValidStamp));
1147 >        };
1148 >        assertNoLongerValidStampsThrow.run();
1149 >
1150 >        for (Function<StampedLock, Long> readLocker : readLockers())
1151 >        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
1152 >            final long stamp = readLocker.apply(sl);
1153 >            assertValid(sl, stamp);
1154 >            assertNoLongerValidStampsThrow.run();
1155 >            assertThrows(IllegalMonitorStateException.class,
1156 >                         () -> sl.unlockWrite(stamp),
1157 >                         () -> sl.unlockRead(sl.tryOptimisticRead()),
1158 >                         () -> sl.unlockRead(0L));
1159 >            readUnlocker.accept(sl, stamp);
1160 >            assertUnlocked(sl);
1161 >            assertNoLongerValidStampsThrow.run();
1162 >        }
1163 >
1164 >        for (Function<StampedLock, Long> writeLocker : writeLockers())
1165 >        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
1166 >            final long stamp = writeLocker.apply(sl);
1167 >            assertValid(sl, stamp);
1168 >            assertNoLongerValidStampsThrow.run();
1169 >            assertThrows(IllegalMonitorStateException.class,
1170 >                         () -> sl.unlockRead(stamp),
1171 >                         () -> sl.unlockWrite(0L));
1172 >            writeUnlocker.accept(sl, stamp);
1173 >            assertUnlocked(sl);
1174 >            assertNoLongerValidStampsThrow.run();
1175 >        }
1176 >    }
1177 >
1178 >    /**
1179 >     * Read locks can be very deeply nested
1180 >     */
1181 >    public void testDeeplyNestedReadLocks() {
1182 >        final StampedLock lock = new StampedLock();
1183 >        final int depth = 300;
1184 >        final long[] stamps = new long[depth];
1185 >        final List<Function<StampedLock, Long>> readLockers = readLockers();
1186 >        final List<BiConsumer<StampedLock, Long>> readUnlockers = readUnlockers();
1187 >        for (int i = 0; i < depth; i++) {
1188 >            Function<StampedLock, Long> readLocker
1189 >                = readLockers.get(i % readLockers.size());
1190 >            long stamp = readLocker.apply(lock);
1191 >            assertEquals(i + 1, lock.getReadLockCount());
1192 >            assertTrue(lock.isReadLocked());
1193 >            stamps[i] = stamp;
1194 >        }
1195 >        for (int i = 0; i < depth; i++) {
1196 >            BiConsumer<StampedLock, Long> readUnlocker
1197 >                = readUnlockers.get(i % readUnlockers.size());
1198 >            assertEquals(depth - i, lock.getReadLockCount());
1199 >            assertTrue(lock.isReadLocked());
1200 >            readUnlocker.accept(lock, stamps[depth - 1 - i]);
1201 >        }
1202 >        assertUnlocked(lock);
1203 >    }
1204 >
1205 >    /**
1206 >     * Stamped locks are not reentrant.
1207 >     */
1208 >    public void testNonReentrant() throws InterruptedException {
1209 >        final StampedLock lock = new StampedLock();
1210 >        long stamp;
1211 >
1212 >        stamp = lock.writeLock();
1213 >        assertValid(lock, stamp);
1214 >        assertEquals(0L, lock.tryWriteLock(0L, DAYS));
1215 >        assertEquals(0L, lock.tryReadLock(0L, DAYS));
1216 >        assertValid(lock, stamp);
1217 >        lock.unlockWrite(stamp);
1218 >
1219 >        stamp = lock.tryWriteLock(1L, DAYS);
1220 >        assertEquals(0L, lock.tryWriteLock(0L, DAYS));
1221 >        assertValid(lock, stamp);
1222 >        lock.unlockWrite(stamp);
1223 >
1224 >        stamp = lock.readLock();
1225 >        assertEquals(0L, lock.tryWriteLock(0L, DAYS));
1226 >        assertValid(lock, stamp);
1227 >        lock.unlockRead(stamp);
1228 >    }
1229 >
1230 >    /**
1231 >     * """StampedLocks have no notion of ownership. Locks acquired in
1232 >     * one thread can be released or converted in another."""
1233 >     */
1234 >    public void testNoOwnership() throws Throwable {
1235 >        ArrayList<Future<?>> futures = new ArrayList<>();
1236 >        for (Function<StampedLock, Long> writeLocker : writeLockers())
1237 >        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
1238 >            StampedLock lock = new StampedLock();
1239 >            long stamp = writeLocker.apply(lock);
1240 >            futures.add(cachedThreadPool.submit(new CheckedRunnable() {
1241 >                public void realRun() {
1242 >                    writeUnlocker.accept(lock, stamp);
1243 >                    assertUnlocked(lock);
1244 >                    assertFalse(lock.validate(stamp));
1245 >                }}));
1246 >        }
1247 >        for (Future<?> future : futures)
1248 >            assertNull(future.get());
1249 >    }
1250 >
1251 >    /** Tries out sample usage code from StampedLock javadoc. */
1252 >    public void testSampleUsage() throws Throwable {
1253 >        class Point {
1254 >            private double x, y;
1255 >            private final StampedLock sl = new StampedLock();
1256 >
1257 >            void move(double deltaX, double deltaY) { // an exclusively locked method
1258 >                long stamp = sl.writeLock();
1259 >                try {
1260 >                    x += deltaX;
1261 >                    y += deltaY;
1262 >                } finally {
1263 >                    sl.unlockWrite(stamp);
1264 >                }
1265 >            }
1266 >
1267 >            double distanceFromOrigin() { // A read-only method
1268 >                double currentX, currentY;
1269 >                long stamp = sl.tryOptimisticRead();
1270 >                do {
1271 >                    if (stamp == 0L)
1272 >                        stamp = sl.readLock();
1273 >                    try {
1274 >                        // possibly racy reads
1275 >                        currentX = x;
1276 >                        currentY = y;
1277 >                    } finally {
1278 >                        stamp = sl.tryConvertToOptimisticRead(stamp);
1279 >                    }
1280 >                } while (stamp == 0);
1281 >                return Math.hypot(currentX, currentY);
1282 >            }
1283 >
1284 >            double distanceFromOrigin2() {
1285 >                long stamp = sl.tryOptimisticRead();
1286 >                try {
1287 >                    retryHoldingLock:
1288 >                    for (;; stamp = sl.readLock()) {
1289 >                        if (stamp == 0L)
1290 >                            continue retryHoldingLock;
1291 >                        // possibly racy reads
1292 >                        double currentX = x;
1293 >                        double currentY = y;
1294 >                        if (!sl.validate(stamp))
1295 >                            continue retryHoldingLock;
1296 >                        return Math.hypot(currentX, currentY);
1297 >                    }
1298 >                } finally {
1299 >                    if (StampedLock.isReadLockStamp(stamp))
1300 >                        sl.unlockRead(stamp);
1301 >                }
1302 >            }
1303 >
1304 >            void moveIfAtOrigin(double newX, double newY) {
1305 >                long stamp = sl.readLock();
1306 >                try {
1307 >                    while (x == 0.0 && y == 0.0) {
1308 >                        long ws = sl.tryConvertToWriteLock(stamp);
1309 >                        if (ws != 0L) {
1310 >                            stamp = ws;
1311 >                            x = newX;
1312 >                            y = newY;
1313 >                            return;
1314 >                        }
1315 >                        else {
1316 >                            sl.unlockRead(stamp);
1317 >                            stamp = sl.writeLock();
1318 >                        }
1319 >                    }
1320 >                } finally {
1321 >                    sl.unlock(stamp);
1322 >                }
1323 >            }
1324 >        }
1325 >
1326 >        Point p = new Point();
1327 >        p.move(3.0, 4.0);
1328 >        assertEquals(5.0, p.distanceFromOrigin());
1329 >        p.moveIfAtOrigin(5.0, 12.0);
1330 >        assertEquals(5.0, p.distanceFromOrigin2());
1331 >    }
1332 >
1333 >    /**
1334 >     * Stamp inspection methods work as expected, and do not inspect
1335 >     * the state of the lock itself.
1336 >     */
1337 >    public void testStampStateInspectionMethods() {
1338 >        StampedLock lock = new StampedLock();
1339 >
1340 >        assertFalse(isWriteLockStamp(0L));
1341 >        assertFalse(isReadLockStamp(0L));
1342 >        assertFalse(isLockStamp(0L));
1343 >        assertFalse(isOptimisticReadStamp(0L));
1344 >
1345 >        {
1346 >            long stamp = lock.writeLock();
1347 >            for (int i = 0; i < 2; i++) {
1348 >                assertTrue(isWriteLockStamp(stamp));
1349 >                assertFalse(isReadLockStamp(stamp));
1350 >                assertTrue(isLockStamp(stamp));
1351 >                assertFalse(isOptimisticReadStamp(stamp));
1352 >                if (i == 0)
1353 >                    lock.unlockWrite(stamp);
1354 >            }
1355 >        }
1356 >
1357 >        {
1358 >            long stamp = lock.readLock();
1359 >            for (int i = 0; i < 2; i++) {
1360 >                assertFalse(isWriteLockStamp(stamp));
1361 >                assertTrue(isReadLockStamp(stamp));
1362 >                assertTrue(isLockStamp(stamp));
1363 >                assertFalse(isOptimisticReadStamp(stamp));
1364 >                if (i == 0)
1365 >                    lock.unlockRead(stamp);
1366 >            }
1367 >        }
1368 >
1369 >        {
1370 >            long optimisticStamp = lock.tryOptimisticRead();
1371 >            long readStamp = lock.tryConvertToReadLock(optimisticStamp);
1372 >            long writeStamp = lock.tryConvertToWriteLock(readStamp);
1373 >            for (int i = 0; i < 2; i++) {
1374 >                assertFalse(isWriteLockStamp(optimisticStamp));
1375 >                assertFalse(isReadLockStamp(optimisticStamp));
1376 >                assertFalse(isLockStamp(optimisticStamp));
1377 >                assertTrue(isOptimisticReadStamp(optimisticStamp));
1378 >
1379 >                assertFalse(isWriteLockStamp(readStamp));
1380 >                assertTrue(isReadLockStamp(readStamp));
1381 >                assertTrue(isLockStamp(readStamp));
1382 >                assertFalse(isOptimisticReadStamp(readStamp));
1383 >
1384 >                assertTrue(isWriteLockStamp(writeStamp));
1385 >                assertFalse(isReadLockStamp(writeStamp));
1386 >                assertTrue(isLockStamp(writeStamp));
1387 >                assertFalse(isOptimisticReadStamp(writeStamp));
1388 >                if (i == 0)
1389 >                    lock.unlockWrite(writeStamp);
1390 >            }
1391 >        }
1392 >    }
1393 >
1394 >    /**
1395 >     * Multiple threads repeatedly contend for the same lock.
1396 >     */
1397 >    public void testConcurrentAccess() throws Exception {
1398 >        final StampedLock sl = new StampedLock();
1399 >        final Lock wl = sl.asWriteLock();
1400 >        final Lock rl = sl.asReadLock();
1401 >        final long testDurationMillis = expensiveTests ? 1000 : 2;
1402 >        final int nTasks = ThreadLocalRandom.current().nextInt(1, 10);
1403 >        final AtomicBoolean done = new AtomicBoolean(false);
1404 >        final List<CompletableFuture<?>> futures = new ArrayList<>();
1405 >        final List<Callable<Long>> stampedWriteLockers = List.of(
1406 >            () -> sl.writeLock(),
1407 >            () -> writeLockInterruptiblyUninterrupted(sl),
1408 >            () -> tryWriteLockUninterrupted(sl, LONG_DELAY_MS, MILLISECONDS),
1409 >            () -> {
1410 >                long stamp;
1411 >                do { stamp = sl.tryConvertToWriteLock(sl.tryOptimisticRead()); }
1412 >                while (stamp == 0L);
1413 >                return stamp;
1414 >            },
1415 >            () -> {
1416 >              long stamp;
1417 >              do { stamp = sl.tryWriteLock(); } while (stamp == 0L);
1418 >              return stamp;
1419 >            },
1420 >            () -> {
1421 >              long stamp;
1422 >              do { stamp = sl.tryWriteLock(0L, DAYS); } while (stamp == 0L);
1423 >              return stamp;
1424 >            });
1425 >        final List<Callable<Long>> stampedReadLockers = List.of(
1426 >            () -> sl.readLock(),
1427 >            () -> readLockInterruptiblyUninterrupted(sl),
1428 >            () -> tryReadLockUninterrupted(sl, LONG_DELAY_MS, MILLISECONDS),
1429 >            () -> {
1430 >                long stamp;
1431 >                do { stamp = sl.tryConvertToReadLock(sl.tryOptimisticRead()); }
1432 >                while (stamp == 0L);
1433 >                return stamp;
1434 >            },
1435 >            () -> {
1436 >              long stamp;
1437 >              do { stamp = sl.tryReadLock(); } while (stamp == 0L);
1438 >              return stamp;
1439 >            },
1440 >            () -> {
1441 >              long stamp;
1442 >              do { stamp = sl.tryReadLock(0L, DAYS); } while (stamp == 0L);
1443 >              return stamp;
1444 >            });
1445 >        final List<Consumer<Long>> stampedWriteUnlockers = List.of(
1446 >            stamp -> sl.unlockWrite(stamp),
1447 >            stamp -> sl.unlock(stamp),
1448 >            stamp -> assertTrue(sl.tryUnlockWrite()),
1449 >            stamp -> wl.unlock(),
1450 >            stamp -> sl.tryConvertToOptimisticRead(stamp));
1451 >        final List<Consumer<Long>> stampedReadUnlockers = List.of(
1452 >            stamp -> sl.unlockRead(stamp),
1453 >            stamp -> sl.unlock(stamp),
1454 >            stamp -> assertTrue(sl.tryUnlockRead()),
1455 >            stamp -> rl.unlock(),
1456 >            stamp -> sl.tryConvertToOptimisticRead(stamp));
1457 >        final Action writer = () -> {
1458 >            // repeatedly acquires write lock
1459 >            var locker = chooseRandomly(stampedWriteLockers);
1460 >            var unlocker = chooseRandomly(stampedWriteUnlockers);
1461 >            while (!done.getAcquire()) {
1462 >                long stamp = locker.call();
1463 >                try {
1464 >                    assertTrue(isWriteLockStamp(stamp));
1465 >                    assertTrue(sl.isWriteLocked());
1466 >                    assertFalse(isReadLockStamp(stamp));
1467 >                    assertFalse(sl.isReadLocked());
1468 >                    assertEquals(0, sl.getReadLockCount());
1469 >                    assertTrue(sl.validate(stamp));
1470 >                } finally {
1471 >                    unlocker.accept(stamp);
1472 >                }
1473 >            }
1474 >        };
1475 >        final Action reader = () -> {
1476 >            // repeatedly acquires read lock
1477 >            var locker = chooseRandomly(stampedReadLockers);
1478 >            var unlocker = chooseRandomly(stampedReadUnlockers);
1479 >            while (!done.getAcquire()) {
1480 >                long stamp = locker.call();
1481 >                try {
1482 >                    assertFalse(isWriteLockStamp(stamp));
1483 >                    assertFalse(sl.isWriteLocked());
1484 >                    assertTrue(isReadLockStamp(stamp));
1485 >                    assertTrue(sl.isReadLocked());
1486 >                    assertTrue(sl.getReadLockCount() > 0);
1487 >                    assertTrue(sl.validate(stamp));
1488 >                } finally {
1489 >                    unlocker.accept(stamp);
1490 >                }
1491 >            }
1492 >        };
1493 >        for (int i = nTasks; i--> 0; ) {
1494 >            Action task = chooseRandomly(writer, reader);
1495 >            futures.add(CompletableFuture.runAsync(checkedRunnable(task)));
1496 >        }
1497 >        Thread.sleep(testDurationMillis);
1498 >        done.setRelease(true);
1499 >        for (var future : futures)
1500 >            checkTimedGet(future, null);
1501 >    }
1502  
1503   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines