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.43 by jsr166, Fri Feb 22 19:27:47 2019 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.*;
9 < import java.util.concurrent.atomic.AtomicBoolean;
10 < import java.util.concurrent.locks.Condition;
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.CountDownLatch;
19 > import java.util.concurrent.Future;
20 > import java.util.concurrent.TimeUnit;
21   import java.util.concurrent.locks.Lock;
14 import java.util.concurrent.locks.ReadWriteLock;
22   import java.util.concurrent.locks.StampedLock;
23 < import java.util.concurrent.CountDownLatch;
24 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
25 < import java.util.*;
23 > import java.util.function.BiConsumer;
24 > import java.util.function.Function;
25 >
26 > import junit.framework.Test;
27 > import junit.framework.TestSuite;
28  
29   public class StampedLockTest extends JSR166TestCase {
30      public static void main(String[] args) {
31 <        junit.textui.TestRunner.run(suite());
31 >        main(suite(), args);
32      }
33      public static Test suite() {
34          return new TestSuite(StampedLockTest.class);
35      }
36  
37 <    // XXXX Just a skeleton implementation for now.
38 <    public void testTODO() { fail("StampedLockTest needs help"); }
37 >    /**
38 >     * Releases write lock, checking isWriteLocked before and after
39 >     */
40 >    void releaseWriteLock(StampedLock lock, long stamp) {
41 >        assertTrue(lock.isWriteLocked());
42 >        assertValid(lock, stamp);
43 >        lock.unlockWrite(stamp);
44 >        assertFalse(lock.isWriteLocked());
45 >        assertFalse(lock.validate(stamp));
46 >    }
47 >
48 >    /**
49 >     * Releases read lock, checking isReadLocked before and after
50 >     */
51 >    void releaseReadLock(StampedLock lock, long stamp) {
52 >        assertTrue(lock.isReadLocked());
53 >        assertValid(lock, stamp);
54 >        lock.unlockRead(stamp);
55 >        assertFalse(lock.isReadLocked());
56 >        assertTrue(lock.validate(stamp));
57 >    }
58 >
59 >    long assertNonZero(long v) {
60 >        assertTrue(v != 0L);
61 >        return v;
62 >    }
63 >
64 >    long assertValid(StampedLock lock, long stamp) {
65 >        assertTrue(stamp != 0L);
66 >        assertTrue(lock.validate(stamp));
67 >        return stamp;
68 >    }
69 >
70 >    void assertUnlocked(StampedLock lock) {
71 >        assertFalse(lock.isReadLocked());
72 >        assertFalse(lock.isWriteLocked());
73 >        assertEquals(0, lock.getReadLockCount());
74 >        assertValid(lock, lock.tryOptimisticRead());
75 >    }
76 >
77 >    List<Action> lockLockers(Lock lock) {
78 >        List<Action> lockers = new ArrayList<>();
79 >        lockers.add(() -> lock.lock());
80 >        lockers.add(() -> lock.lockInterruptibly());
81 >        lockers.add(() -> lock.tryLock());
82 >        lockers.add(() -> lock.tryLock(Long.MIN_VALUE, DAYS));
83 >        lockers.add(() -> lock.tryLock(0L, DAYS));
84 >        lockers.add(() -> lock.tryLock(Long.MAX_VALUE, DAYS));
85 >        return lockers;
86 >    }
87 >
88 >    List<Function<StampedLock, Long>> readLockers() {
89 >        List<Function<StampedLock, Long>> readLockers = new ArrayList<>();
90 >        readLockers.add(sl -> sl.readLock());
91 >        readLockers.add(sl -> sl.tryReadLock());
92 >        readLockers.add(sl -> readLockInterruptiblyUninterrupted(sl));
93 >        readLockers.add(sl -> tryReadLockUninterrupted(sl, Long.MIN_VALUE, DAYS));
94 >        readLockers.add(sl -> tryReadLockUninterrupted(sl, 0L, DAYS));
95 >        readLockers.add(sl -> sl.tryConvertToReadLock(sl.tryOptimisticRead()));
96 >        return readLockers;
97 >    }
98 >
99 >    List<BiConsumer<StampedLock, Long>> readUnlockers() {
100 >        List<BiConsumer<StampedLock, Long>> readUnlockers = new ArrayList<>();
101 >        readUnlockers.add((sl, stamp) -> sl.unlockRead(stamp));
102 >        readUnlockers.add((sl, stamp) -> assertTrue(sl.tryUnlockRead()));
103 >        readUnlockers.add((sl, stamp) -> sl.asReadLock().unlock());
104 >        readUnlockers.add((sl, stamp) -> sl.unlock(stamp));
105 >        readUnlockers.add((sl, stamp) -> assertValid(sl, sl.tryConvertToOptimisticRead(stamp)));
106 >        return readUnlockers;
107 >    }
108 >
109 >    List<Function<StampedLock, Long>> writeLockers() {
110 >        List<Function<StampedLock, Long>> writeLockers = new ArrayList<>();
111 >        writeLockers.add(sl -> sl.writeLock());
112 >        writeLockers.add(sl -> sl.tryWriteLock());
113 >        writeLockers.add(sl -> writeLockInterruptiblyUninterrupted(sl));
114 >        writeLockers.add(sl -> tryWriteLockUninterrupted(sl, Long.MIN_VALUE, DAYS));
115 >        writeLockers.add(sl -> tryWriteLockUninterrupted(sl, 0L, DAYS));
116 >        writeLockers.add(sl -> sl.tryConvertToWriteLock(sl.tryOptimisticRead()));
117 >        return writeLockers;
118 >    }
119 >
120 >    List<BiConsumer<StampedLock, Long>> writeUnlockers() {
121 >        List<BiConsumer<StampedLock, Long>> writeUnlockers = new ArrayList<>();
122 >        writeUnlockers.add((sl, stamp) -> sl.unlockWrite(stamp));
123 >        writeUnlockers.add((sl, stamp) -> assertTrue(sl.tryUnlockWrite()));
124 >        writeUnlockers.add((sl, stamp) -> sl.asWriteLock().unlock());
125 >        writeUnlockers.add((sl, stamp) -> sl.unlock(stamp));
126 >        writeUnlockers.add((sl, stamp) -> assertValid(sl, sl.tryConvertToOptimisticRead(stamp)));
127 >        return writeUnlockers;
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 >    /**
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 s = 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 >
363 >    /**
364 >     * interruptible operations throw InterruptedException when read locked and interrupted
365 >     */
366 >    public void testInterruptibleOperationsThrowInterruptedExceptionReadLockedInterrupted() {
367 >        final StampedLock lock = new StampedLock();
368 >        long s = lock.readLock();
369 >
370 >        Action[] interruptibleLockBlockingActions = {
371 >            () -> lock.writeLockInterruptibly(),
372 >            () -> lock.tryWriteLock(Long.MAX_VALUE, DAYS),
373 >            () -> lock.asWriteLock().lockInterruptibly(),
374 >            () -> lock.asWriteLock().tryLock(Long.MAX_VALUE, DAYS),
375 >        };
376 >        shuffle(interruptibleLockBlockingActions);
377 >
378 >        assertThrowInterruptedExceptionWhenInterrupted(interruptibleLockBlockingActions);
379 >    }
380 >
381 >    /**
382 >     * Non-interruptible operations ignore and preserve interrupt status
383 >     */
384 >    public void testNonInterruptibleOperationsIgnoreInterrupts() {
385 >        final StampedLock lock = new StampedLock();
386 >        Thread.currentThread().interrupt();
387 >
388 >        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
389 >            long s = assertValid(lock, lock.readLock());
390 >            readUnlocker.accept(lock, s);
391 >            s = assertValid(lock, lock.tryReadLock());
392 >            readUnlocker.accept(lock, s);
393 >        }
394 >
395 >        lock.asReadLock().lock();
396 >        lock.asReadLock().unlock();
397 >
398 >        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
399 >            long s = assertValid(lock, lock.writeLock());
400 >            writeUnlocker.accept(lock, s);
401 >            s = assertValid(lock, lock.tryWriteLock());
402 >            writeUnlocker.accept(lock, s);
403 >        }
404 >
405 >        lock.asWriteLock().lock();
406 >        lock.asWriteLock().unlock();
407 >
408 >        assertTrue(Thread.interrupted());
409 >    }
410 >
411 >    /**
412 >     * tryWriteLock on an unlocked lock succeeds
413 >     */
414 >    public void testTryWriteLock() {
415 >        final StampedLock lock = new StampedLock();
416 >        long s = lock.tryWriteLock();
417 >        assertTrue(s != 0L);
418 >        assertTrue(lock.isWriteLocked());
419 >        assertEquals(0L, lock.tryWriteLock());
420 >        releaseWriteLock(lock, s);
421 >    }
422 >
423 >    /**
424 >     * tryWriteLock fails if locked
425 >     */
426 >    public void testTryWriteLockWhenLocked() {
427 >        final StampedLock lock = new StampedLock();
428 >        long s = lock.writeLock();
429 >        Thread t = newStartedThread(new CheckedRunnable() {
430 >            public void realRun() {
431 >                assertEquals(0L, lock.tryWriteLock());
432 >            }});
433 >
434 >        assertEquals(0L, lock.tryWriteLock());
435 >        awaitTermination(t);
436 >        releaseWriteLock(lock, s);
437 >    }
438 >
439 >    /**
440 >     * tryReadLock fails if write-locked
441 >     */
442 >    public void testTryReadLockWhenLocked() {
443 >        final StampedLock lock = new StampedLock();
444 >        long s = lock.writeLock();
445 >        Thread t = newStartedThread(new CheckedRunnable() {
446 >            public void realRun() {
447 >                assertEquals(0L, lock.tryReadLock());
448 >            }});
449 >
450 >        assertEquals(0L, lock.tryReadLock());
451 >        awaitTermination(t);
452 >        releaseWriteLock(lock, s);
453 >    }
454 >
455 >    /**
456 >     * Multiple threads can hold a read lock when not write-locked
457 >     */
458 >    public void testMultipleReadLocks() {
459 >        final StampedLock lock = new StampedLock();
460 >        final long s = lock.readLock();
461 >        Thread t = newStartedThread(new CheckedRunnable() {
462 >            public void realRun() throws InterruptedException {
463 >                long s2 = lock.tryReadLock();
464 >                assertValid(lock, s2);
465 >                lock.unlockRead(s2);
466 >                long s3 = lock.tryReadLock(LONG_DELAY_MS, MILLISECONDS);
467 >                assertValid(lock, s3);
468 >                lock.unlockRead(s3);
469 >                long s4 = lock.readLock();
470 >                assertValid(lock, s4);
471 >                lock.unlockRead(s4);
472 >                lock.asReadLock().lock();
473 >                lock.asReadLock().unlock();
474 >                lock.asReadLock().lockInterruptibly();
475 >                lock.asReadLock().unlock();
476 >                lock.asReadLock().tryLock(Long.MIN_VALUE, DAYS);
477 >                lock.asReadLock().unlock();
478 >            }});
479 >
480 >        awaitTermination(t);
481 >        lock.unlockRead(s);
482 >    }
483 >
484 >    /**
485 >     * writeLock() succeeds only after a reading thread unlocks
486 >     */
487 >    public void testWriteAfterReadLock() throws InterruptedException {
488 >        final CountDownLatch aboutToLock = new CountDownLatch(1);
489 >        final StampedLock lock = new StampedLock();
490 >        long rs = lock.readLock();
491 >        Thread t = newStartedThread(new CheckedRunnable() {
492 >            public void realRun() {
493 >                aboutToLock.countDown();
494 >                long s = lock.writeLock();
495 >                assertTrue(lock.isWriteLocked());
496 >                assertFalse(lock.isReadLocked());
497 >                lock.unlockWrite(s);
498 >            }});
499 >
500 >        await(aboutToLock);
501 >        assertThreadBlocks(t, Thread.State.WAITING);
502 >        assertFalse(lock.isWriteLocked());
503 >        assertTrue(lock.isReadLocked());
504 >        lock.unlockRead(rs);
505 >        awaitTermination(t);
506 >        assertUnlocked(lock);
507 >    }
508 >
509 >    /**
510 >     * writeLock() succeeds only after reading threads unlock
511 >     */
512 >    public void testWriteAfterMultipleReadLocks() {
513 >        final StampedLock lock = new StampedLock();
514 >        long s = lock.readLock();
515 >        Thread t1 = newStartedThread(new CheckedRunnable() {
516 >            public void realRun() {
517 >                long rs = lock.readLock();
518 >                lock.unlockRead(rs);
519 >            }});
520 >
521 >        awaitTermination(t1);
522 >
523 >        Thread t2 = newStartedThread(new CheckedRunnable() {
524 >            public void realRun() {
525 >                long ws = lock.writeLock();
526 >                lock.unlockWrite(ws);
527 >            }});
528 >
529 >        assertTrue(lock.isReadLocked());
530 >        assertFalse(lock.isWriteLocked());
531 >        lock.unlockRead(s);
532 >        awaitTermination(t2);
533 >        assertUnlocked(lock);
534 >    }
535 >
536 >    /**
537 >     * readLock() succeed only after a writing thread unlocks
538 >     */
539 >    public void testReadAfterWriteLock() {
540 >        final StampedLock lock = new StampedLock();
541 >        final CountDownLatch threadsStarted = new CountDownLatch(2);
542 >        final long s = lock.writeLock();
543 >        final Runnable acquireReleaseReadLock = new CheckedRunnable() {
544 >            public void realRun() {
545 >                threadsStarted.countDown();
546 >                long rs = lock.readLock();
547 >                assertTrue(lock.isReadLocked());
548 >                assertFalse(lock.isWriteLocked());
549 >                lock.unlockRead(rs);
550 >            }};
551 >        Thread t1 = newStartedThread(acquireReleaseReadLock);
552 >        Thread t2 = newStartedThread(acquireReleaseReadLock);
553 >
554 >        await(threadsStarted);
555 >        assertThreadBlocks(t1, Thread.State.WAITING);
556 >        assertThreadBlocks(t2, Thread.State.WAITING);
557 >        assertTrue(lock.isWriteLocked());
558 >        assertFalse(lock.isReadLocked());
559 >        releaseWriteLock(lock, s);
560 >        awaitTermination(t1);
561 >        awaitTermination(t2);
562 >        assertUnlocked(lock);
563 >    }
564 >
565 >    /**
566 >     * tryReadLock succeeds if read locked but not write locked
567 >     */
568 >    public void testTryLockWhenReadLocked() {
569 >        final StampedLock lock = new StampedLock();
570 >        long s = lock.readLock();
571 >        Thread t = newStartedThread(new CheckedRunnable() {
572 >            public void realRun() {
573 >                long rs = lock.tryReadLock();
574 >                assertValid(lock, rs);
575 >                lock.unlockRead(rs);
576 >            }});
577 >
578 >        awaitTermination(t);
579 >        lock.unlockRead(s);
580 >    }
581 >
582 >    /**
583 >     * tryWriteLock fails when read locked
584 >     */
585 >    public void testTryWriteLockWhenReadLocked() {
586 >        final StampedLock lock = new StampedLock();
587 >        long s = lock.readLock();
588 >        Thread t = newStartedThread(new CheckedRunnable() {
589 >            public void realRun() {
590 >                assertEquals(0L, lock.tryWriteLock());
591 >            }});
592 >
593 >        awaitTermination(t);
594 >        lock.unlockRead(s);
595 >    }
596 >
597 >    /**
598 >     * timed lock operations time out if lock not available
599 >     */
600 >    public void testTimedLock_Timeout() throws Exception {
601 >        ArrayList<Future<?>> futures = new ArrayList<>();
602 >
603 >        // Write locked
604 >        final StampedLock lock = new StampedLock();
605 >        long stamp = lock.writeLock();
606 >        assertEquals(0L, lock.tryReadLock(0L, DAYS));
607 >        assertEquals(0L, lock.tryReadLock(Long.MIN_VALUE, DAYS));
608 >        assertFalse(lock.asReadLock().tryLock(0L, DAYS));
609 >        assertFalse(lock.asReadLock().tryLock(Long.MIN_VALUE, DAYS));
610 >        assertEquals(0L, lock.tryWriteLock(0L, DAYS));
611 >        assertEquals(0L, lock.tryWriteLock(Long.MIN_VALUE, DAYS));
612 >        assertFalse(lock.asWriteLock().tryLock(0L, DAYS));
613 >        assertFalse(lock.asWriteLock().tryLock(Long.MIN_VALUE, DAYS));
614 >
615 >        futures.add(cachedThreadPool.submit(new CheckedRunnable() {
616 >            public void realRun() throws InterruptedException {
617 >                long startTime = System.nanoTime();
618 >                assertEquals(0L, lock.tryWriteLock(timeoutMillis(), MILLISECONDS));
619 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
620 >            }}));
621 >
622 >        futures.add(cachedThreadPool.submit(new CheckedRunnable() {
623 >            public void realRun() throws InterruptedException {
624 >                long startTime = System.nanoTime();
625 >                assertEquals(0L, lock.tryReadLock(timeoutMillis(), MILLISECONDS));
626 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
627 >            }}));
628 >
629 >        // Read locked
630 >        final StampedLock lock2 = new StampedLock();
631 >        long stamp2 = lock2.readLock();
632 >        assertEquals(0L, lock2.tryWriteLock(0L, DAYS));
633 >        assertEquals(0L, lock2.tryWriteLock(Long.MIN_VALUE, DAYS));
634 >        assertFalse(lock2.asWriteLock().tryLock(0L, DAYS));
635 >        assertFalse(lock2.asWriteLock().tryLock(Long.MIN_VALUE, DAYS));
636 >
637 >        futures.add(cachedThreadPool.submit(new CheckedRunnable() {
638 >            public void realRun() throws InterruptedException {
639 >                long startTime = System.nanoTime();
640 >                assertEquals(0L, lock2.tryWriteLock(timeoutMillis(), MILLISECONDS));
641 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
642 >            }}));
643 >
644 >        for (Future<?> future : futures)
645 >            assertNull(future.get());
646 >
647 >        releaseWriteLock(lock, stamp);
648 >        releaseReadLock(lock2, stamp2);
649 >    }
650 >
651 >    /**
652 >     * writeLockInterruptibly succeeds if unlocked
653 >     */
654 >    public void testWriteLockInterruptibly() throws InterruptedException {
655 >        final StampedLock lock = new StampedLock();
656 >        long s = lock.writeLockInterruptibly();
657 >        assertTrue(lock.isWriteLocked());
658 >        releaseWriteLock(lock, s);
659 >    }
660 >
661 >    /**
662 >     * readLockInterruptibly succeeds if lock free
663 >     */
664 >    public void testReadLockInterruptibly() throws InterruptedException {
665 >        final StampedLock lock = new StampedLock();
666 >
667 >        long s = assertValid(lock, lock.readLockInterruptibly());
668 >        assertTrue(lock.isReadLocked());
669 >        lock.unlockRead(s);
670 >
671 >        lock.asReadLock().lockInterruptibly();
672 >        assertTrue(lock.isReadLocked());
673 >        lock.asReadLock().unlock();
674 >    }
675 >
676 >    /**
677 >     * A serialized lock deserializes as unlocked
678 >     */
679 >    public void testSerialization() {
680 >        StampedLock lock = new StampedLock();
681 >        lock.writeLock();
682 >        StampedLock clone = serialClone(lock);
683 >        assertTrue(lock.isWriteLocked());
684 >        assertFalse(clone.isWriteLocked());
685 >        long s = clone.writeLock();
686 >        assertTrue(clone.isWriteLocked());
687 >        clone.unlockWrite(s);
688 >        assertFalse(clone.isWriteLocked());
689 >    }
690  
691 <    public void testConstructor() { new StampedLock(); }
691 >    /**
692 >     * toString indicates current lock state
693 >     */
694 >    public void testToString() {
695 >        StampedLock lock = new StampedLock();
696 >        assertTrue(lock.toString().contains("Unlocked"));
697 >        long s = lock.writeLock();
698 >        assertTrue(lock.toString().contains("Write-locked"));
699 >        lock.unlockWrite(s);
700 >        s = lock.readLock();
701 >        assertTrue(lock.toString().contains("Read-locks"));
702 >    }
703 >
704 >    /**
705 >     * tryOptimisticRead succeeds and validates if unlocked, fails if
706 >     * exclusively locked
707 >     */
708 >    public void testValidateOptimistic() throws InterruptedException {
709 >        StampedLock lock = new StampedLock();
710 >
711 >        assertValid(lock, lock.tryOptimisticRead());
712 >
713 >        for (Function<StampedLock, Long> writeLocker : writeLockers()) {
714 >            long s = assertValid(lock, writeLocker.apply(lock));
715 >            assertEquals(0L, lock.tryOptimisticRead());
716 >            releaseWriteLock(lock, s);
717 >        }
718 >
719 >        for (Function<StampedLock, Long> readLocker : readLockers()) {
720 >            long s = assertValid(lock, readLocker.apply(lock));
721 >            long p = assertValid(lock, lock.tryOptimisticRead());
722 >            releaseReadLock(lock, s);
723 >            assertTrue(lock.validate(p));
724 >        }
725 >
726 >        assertValid(lock, lock.tryOptimisticRead());
727 >    }
728 >
729 >    /**
730 >     * tryOptimisticRead stamp does not validate if a write lock intervenes
731 >     */
732 >    public void testValidateOptimisticWriteLocked() {
733 >        final StampedLock lock = new StampedLock();
734 >        final long p = assertValid(lock, lock.tryOptimisticRead());
735 >        final long s = assertValid(lock, lock.writeLock());
736 >        assertFalse(lock.validate(p));
737 >        assertEquals(0L, lock.tryOptimisticRead());
738 >        assertTrue(lock.validate(s));
739 >        lock.unlockWrite(s);
740 >    }
741 >
742 >    /**
743 >     * tryOptimisticRead stamp does not validate if a write lock
744 >     * intervenes in another thread
745 >     */
746 >    public void testValidateOptimisticWriteLocked2()
747 >            throws InterruptedException {
748 >        final CountDownLatch locked = new CountDownLatch(1);
749 >        final StampedLock lock = new StampedLock();
750 >        final long p = assertValid(lock, lock.tryOptimisticRead());
751 >
752 >        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
753 >            public void realRun() throws InterruptedException {
754 >                lock.writeLockInterruptibly();
755 >                locked.countDown();
756 >                lock.writeLockInterruptibly();
757 >            }});
758 >
759 >        await(locked);
760 >        assertFalse(lock.validate(p));
761 >        assertEquals(0L, lock.tryOptimisticRead());
762 >        assertThreadBlocks(t, Thread.State.WAITING);
763 >        t.interrupt();
764 >        awaitTermination(t);
765 >        assertTrue(lock.isWriteLocked());
766 >    }
767 >
768 >    /**
769 >     * tryConvertToOptimisticRead succeeds and validates if successfully locked
770 >     */
771 >    public void testTryConvertToOptimisticRead() throws InterruptedException {
772 >        StampedLock lock = new StampedLock();
773 >        long s, p, q;
774 >        assertEquals(0L, lock.tryConvertToOptimisticRead(0L));
775 >
776 >        s = assertValid(lock, lock.tryOptimisticRead());
777 >        assertEquals(s, lock.tryConvertToOptimisticRead(s));
778 >        assertTrue(lock.validate(s));
779 >
780 >        for (Function<StampedLock, Long> writeLocker : writeLockers()) {
781 >            s = assertValid(lock, writeLocker.apply(lock));
782 >            p = assertValid(lock, lock.tryConvertToOptimisticRead(s));
783 >            assertFalse(lock.validate(s));
784 >            assertTrue(lock.validate(p));
785 >            assertUnlocked(lock);
786 >        }
787 >
788 >        for (Function<StampedLock, Long> readLocker : readLockers()) {
789 >            s = assertValid(lock, readLocker.apply(lock));
790 >            q = assertValid(lock, lock.tryOptimisticRead());
791 >            assertEquals(q, lock.tryConvertToOptimisticRead(q));
792 >            assertTrue(lock.validate(q));
793 >            assertTrue(lock.isReadLocked());
794 >            p = assertValid(lock, lock.tryConvertToOptimisticRead(s));
795 >            assertTrue(lock.validate(p));
796 >            assertTrue(lock.validate(s));
797 >            assertUnlocked(lock);
798 >            assertEquals(q, lock.tryConvertToOptimisticRead(q));
799 >            assertTrue(lock.validate(q));
800 >        }
801 >    }
802 >
803 >    /**
804 >     * tryConvertToReadLock succeeds for valid stamps
805 >     */
806 >    public void testTryConvertToReadLock() throws InterruptedException {
807 >        StampedLock lock = new StampedLock();
808 >        long s, p;
809 >
810 >        assertEquals(0L, lock.tryConvertToReadLock(0L));
811 >
812 >        s = assertValid(lock, lock.tryOptimisticRead());
813 >        p = assertValid(lock, lock.tryConvertToReadLock(s));
814 >        assertTrue(lock.isReadLocked());
815 >        assertEquals(1, lock.getReadLockCount());
816 >        assertTrue(lock.validate(s));
817 >        lock.unlockRead(p);
818 >
819 >        s = assertValid(lock, lock.tryOptimisticRead());
820 >        lock.readLock();
821 >        p = assertValid(lock, lock.tryConvertToReadLock(s));
822 >        assertTrue(lock.isReadLocked());
823 >        assertEquals(2, lock.getReadLockCount());
824 >        lock.unlockRead(p);
825 >        lock.unlockRead(p);
826 >        assertUnlocked(lock);
827 >
828 >        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
829 >            for (Function<StampedLock, Long> writeLocker : writeLockers()) {
830 >                s = assertValid(lock, writeLocker.apply(lock));
831 >                p = assertValid(lock, lock.tryConvertToReadLock(s));
832 >                assertFalse(lock.validate(s));
833 >                assertTrue(lock.isReadLocked());
834 >                assertEquals(1, lock.getReadLockCount());
835 >                readUnlocker.accept(lock, p);
836 >            }
837 >
838 >            for (Function<StampedLock, Long> readLocker : readLockers()) {
839 >                s = assertValid(lock, readLocker.apply(lock));
840 >                assertEquals(s, lock.tryConvertToReadLock(s));
841 >                assertTrue(lock.validate(s));
842 >                assertTrue(lock.isReadLocked());
843 >                assertEquals(1, lock.getReadLockCount());
844 >                readUnlocker.accept(lock, s);
845 >            }
846 >        }
847 >    }
848  
849 < //     /**
850 < //      * A runnable calling lockInterruptibly
851 < //      */
852 < //     class InterruptibleLockRunnable extends CheckedRunnable {
853 < //         final ReentrantReadWriteLock lock;
854 < //         InterruptibleLockRunnable(ReentrantReadWriteLock l) { lock = l; }
855 < //         public void realRun() throws InterruptedException {
856 < //             lock.writeLock().lockInterruptibly();
857 < //         }
858 < //     }
859 <
860 < //     /**
861 < //      * A runnable calling lockInterruptibly that expects to be
862 < //      * interrupted
863 < //      */
864 < //     class InterruptedLockRunnable extends CheckedInterruptedRunnable {
865 < //         final ReentrantReadWriteLock lock;
866 < //         InterruptedLockRunnable(ReentrantReadWriteLock l) { lock = l; }
867 < //         public void realRun() throws InterruptedException {
868 < //             lock.writeLock().lockInterruptibly();
869 < //         }
870 < //     }
871 <
872 < //     /**
873 < //      * Subclass to expose protected methods
874 < //      */
875 < //     static class PublicReentrantReadWriteLock extends ReentrantReadWriteLock {
876 < //         PublicReentrantReadWriteLock() { super(); }
877 < //         PublicReentrantReadWriteLock(boolean fair) { super(fair); }
878 < //         public Thread getOwner() {
879 < //             return super.getOwner();
880 < //         }
881 < //         public Collection<Thread> getQueuedThreads() {
882 < //             return super.getQueuedThreads();
883 < //         }
884 < //         public Collection<Thread> getWaitingThreads(Condition c) {
885 < //             return super.getWaitingThreads(c);
886 < //         }
887 < //     }
888 <
889 < //     /**
890 < //      * Releases write lock, checking that it had a hold count of 1.
891 < //      */
892 < //     void releaseWriteLock(PublicReentrantReadWriteLock lock) {
893 < //         ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
894 < //         assertWriteLockedByMoi(lock);
895 < //         assertEquals(1, lock.getWriteHoldCount());
896 < //         writeLock.unlock();
897 < //         assertNotWriteLocked(lock);
898 < //     }
899 <
900 < //     /**
901 < //      * Spin-waits until lock.hasQueuedThread(t) becomes true.
902 < //      */
903 < //     void waitForQueuedThread(PublicReentrantReadWriteLock lock, Thread t) {
904 < //         long startTime = System.nanoTime();
905 < //         while (!lock.hasQueuedThread(t)) {
906 < //             if (millisElapsedSince(startTime) > LONG_DELAY_MS)
907 < //                 throw new AssertionFailedError("timed out");
908 < //             Thread.yield();
909 < //         }
910 < //         assertTrue(t.isAlive());
911 < //         assertTrue(lock.getOwner() != t);
912 < //     }
913 <
914 < //     /**
915 < //      * Checks that lock is not write-locked.
916 < //      */
917 < //     void assertNotWriteLocked(PublicReentrantReadWriteLock lock) {
918 < //         assertFalse(lock.isWriteLocked());
919 < //         assertFalse(lock.isWriteLockedByCurrentThread());
920 < //         assertFalse(lock.writeLock().isHeldByCurrentThread());
921 < //         assertEquals(0, lock.getWriteHoldCount());
922 < //         assertEquals(0, lock.writeLock().getHoldCount());
923 < //         assertNull(lock.getOwner());
924 < //     }
925 <
926 < //     /**
927 < //      * Checks that lock is write-locked by the given thread.
928 < //      */
929 < //     void assertWriteLockedBy(PublicReentrantReadWriteLock lock, Thread t) {
930 < //         assertTrue(lock.isWriteLocked());
931 < //         assertSame(t, lock.getOwner());
932 < //         assertEquals(t == Thread.currentThread(),
933 < //                      lock.isWriteLockedByCurrentThread());
934 < //         assertEquals(t == Thread.currentThread(),
935 < //                      lock.writeLock().isHeldByCurrentThread());
936 < //         assertEquals(t == Thread.currentThread(),
937 < //                      lock.getWriteHoldCount() > 0);
938 < //         assertEquals(t == Thread.currentThread(),
939 < //                      lock.writeLock().getHoldCount() > 0);
940 < //         assertEquals(0, lock.getReadLockCount());
941 < //     }
942 <
943 < //     /**
944 < //      * Checks that lock is write-locked by the current thread.
945 < //      */
946 < //     void assertWriteLockedByMoi(PublicReentrantReadWriteLock lock) {
947 < //         assertWriteLockedBy(lock, Thread.currentThread());
948 < //     }
949 <
950 < //     /**
951 < //      * Checks that condition c has no waiters.
952 < //      */
953 < //     void assertHasNoWaiters(PublicReentrantReadWriteLock lock, Condition c) {
954 < //         assertHasWaiters(lock, c, new Thread[] {});
955 < //     }
956 <
957 < //     /**
958 < //      * Checks that condition c has exactly the given waiter threads.
959 < //      */
960 < //     void assertHasWaiters(PublicReentrantReadWriteLock lock, Condition c,
961 < //                           Thread... threads) {
962 < //         lock.writeLock().lock();
963 < //         assertEquals(threads.length > 0, lock.hasWaiters(c));
964 < //         assertEquals(threads.length, lock.getWaitQueueLength(c));
965 < //         assertEquals(threads.length == 0, lock.getWaitingThreads(c).isEmpty());
966 < //         assertEquals(threads.length, lock.getWaitingThreads(c).size());
967 < //         assertEquals(new HashSet<Thread>(lock.getWaitingThreads(c)),
968 < //                      new HashSet<Thread>(Arrays.asList(threads)));
969 < //         lock.writeLock().unlock();
970 < //     }
971 <
972 < //     enum AwaitMethod { await, awaitTimed, awaitNanos, awaitUntil };
973 <
974 < //     /**
975 < //      * Awaits condition using the specified AwaitMethod.
976 < //      */
977 < //     void await(Condition c, AwaitMethod awaitMethod)
978 < //             throws InterruptedException {
979 < //         switch (awaitMethod) {
980 < //         case await:
981 < //             c.await();
982 < //             break;
983 < //         case awaitTimed:
984 < //             assertTrue(c.await(2 * LONG_DELAY_MS, MILLISECONDS));
985 < //             break;
986 < //         case awaitNanos:
987 < //             long nanosRemaining = c.awaitNanos(MILLISECONDS.toNanos(2 * LONG_DELAY_MS));
988 < //             assertTrue(nanosRemaining > 0);
989 < //             break;
990 < //         case awaitUntil:
991 < //             java.util.Date d = new java.util.Date();
992 < //             assertTrue(c.awaitUntil(new java.util.Date(d.getTime() + 2 * LONG_DELAY_MS)));
993 < //             break;
994 < //         }
995 < //     }
996 <
997 < //     /**
998 < //      * Constructor sets given fairness, and is in unlocked state
999 < //      */
1000 < //     public void testConstructor() {
1001 < //         PublicReentrantReadWriteLock lock;
1002 <
1003 < //         lock = new PublicReentrantReadWriteLock();
1004 < //         assertFalse(lock.isFair());
1005 < //         assertNotWriteLocked(lock);
1006 < //         assertEquals(0, lock.getReadLockCount());
1007 <
1008 < //         lock = new PublicReentrantReadWriteLock(true);
1009 < //         assertTrue(lock.isFair());
1010 < //         assertNotWriteLocked(lock);
1011 < //         assertEquals(0, lock.getReadLockCount());
1012 <
1013 < //         lock = new PublicReentrantReadWriteLock(false);
1014 < //         assertFalse(lock.isFair());
1015 < //         assertNotWriteLocked(lock);
1016 < //         assertEquals(0, lock.getReadLockCount());
1017 < //     }
1018 <
1019 < //     /**
1020 < //      * write-locking and read-locking an unlocked lock succeed
1021 < //      */
1022 < //     public void testLock()      { testLock(false); }
1023 < //     public void testLock_fair() { testLock(true); }
1024 < //     public void testLock(boolean fair) {
1025 < //         PublicReentrantReadWriteLock lock =
1026 < //             new PublicReentrantReadWriteLock(fair);
1027 < //         assertNotWriteLocked(lock);
1028 < //         lock.writeLock().lock();
1029 < //         assertWriteLockedByMoi(lock);
1030 < //         lock.writeLock().unlock();
1031 < //         assertNotWriteLocked(lock);
1032 < //         assertEquals(0, lock.getReadLockCount());
1033 < //         lock.readLock().lock();
1034 < //         assertNotWriteLocked(lock);
1035 < //         assertEquals(1, lock.getReadLockCount());
1036 < //         lock.readLock().unlock();
1037 < //         assertNotWriteLocked(lock);
1038 < //         assertEquals(0, lock.getReadLockCount());
1039 < //     }
1040 <
1041 < //     /**
1042 < //      * getWriteHoldCount returns number of recursive holds
1043 < //      */
1044 < //     public void testGetWriteHoldCount()      { testGetWriteHoldCount(false); }
1045 < //     public void testGetWriteHoldCount_fair() { testGetWriteHoldCount(true); }
1046 < //     public void testGetWriteHoldCount(boolean fair) {
1047 < //         ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1048 < //         for (int i = 1; i <= SIZE; i++) {
1049 < //             lock.writeLock().lock();
1050 < //             assertEquals(i,lock.getWriteHoldCount());
1051 < //         }
1052 < //         for (int i = SIZE; i > 0; i--) {
1053 < //             lock.writeLock().unlock();
1054 < //             assertEquals(i-1,lock.getWriteHoldCount());
1055 < //         }
1056 < //     }
1057 <
1058 < //     /**
1059 < //      * writelock.getHoldCount returns number of recursive holds
1060 < //      */
1061 < //     public void testGetHoldCount()      { testGetHoldCount(false); }
1062 < //     public void testGetHoldCount_fair() { testGetHoldCount(true); }
1063 < //     public void testGetHoldCount(boolean fair) {
1064 < //         ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1065 < //         for (int i = 1; i <= SIZE; i++) {
1066 < //             lock.writeLock().lock();
1067 < //             assertEquals(i,lock.writeLock().getHoldCount());
1068 < //         }
1069 < //         for (int i = SIZE; i > 0; i--) {
1070 < //             lock.writeLock().unlock();
1071 < //             assertEquals(i-1,lock.writeLock().getHoldCount());
1072 < //         }
1073 < //     }
1074 <
1075 < //     /**
1076 < //      * getReadHoldCount returns number of recursive holds
1077 < //      */
1078 < //     public void testGetReadHoldCount()      { testGetReadHoldCount(false); }
1079 < //     public void testGetReadHoldCount_fair() { testGetReadHoldCount(true); }
1080 < //     public void testGetReadHoldCount(boolean fair) {
1081 < //         ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1082 < //         for (int i = 1; i <= SIZE; i++) {
1083 < //             lock.readLock().lock();
1084 < //             assertEquals(i,lock.getReadHoldCount());
1085 < //         }
1086 < //         for (int i = SIZE; i > 0; i--) {
1087 < //             lock.readLock().unlock();
1088 < //             assertEquals(i-1,lock.getReadHoldCount());
1089 < //         }
1090 < //     }
1091 <
1092 < //     /**
1093 < //      * write-unlocking an unlocked lock throws IllegalMonitorStateException
1094 < //      */
1095 < //     public void testWriteUnlock_IMSE()      { testWriteUnlock_IMSE(false); }
1096 < //     public void testWriteUnlock_IMSE_fair() { testWriteUnlock_IMSE(true); }
1097 < //     public void testWriteUnlock_IMSE(boolean fair) {
1098 < //         ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1099 < //         try {
1100 < //             lock.writeLock().unlock();
1101 < //             shouldThrow();
1102 < //         } catch (IllegalMonitorStateException success) {}
1103 < //     }
1104 <
1105 < //     /**
1106 < //      * read-unlocking an unlocked lock throws IllegalMonitorStateException
1107 < //      */
1108 < //     public void testReadUnlock_IMSE()      { testReadUnlock_IMSE(false); }
1109 < //     public void testReadUnlock_IMSE_fair() { testReadUnlock_IMSE(true); }
1110 < //     public void testReadUnlock_IMSE(boolean fair) {
1111 < //         ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1112 < //         try {
1113 < //             lock.readLock().unlock();
1114 < //             shouldThrow();
1115 < //         } catch (IllegalMonitorStateException success) {}
1116 < //     }
1117 <
1118 < //     /**
1119 < //      * write-lockInterruptibly is interruptible
1120 < //      */
1121 < //     public void testWriteLockInterruptibly_Interruptible()      { testWriteLockInterruptibly_Interruptible(false); }
1122 < //     public void testWriteLockInterruptibly_Interruptible_fair() { testWriteLockInterruptibly_Interruptible(true); }
1123 < //     public void testWriteLockInterruptibly_Interruptible(boolean fair) {
1124 < //         final PublicReentrantReadWriteLock lock =
1125 < //             new PublicReentrantReadWriteLock(fair);
1126 < //         lock.writeLock().lock();
1127 < //         Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1128 < //             public void realRun() throws InterruptedException {
1129 < //                 lock.writeLock().lockInterruptibly();
1130 < //             }});
1131 <
1132 < //         waitForQueuedThread(lock, t);
1133 < //         t.interrupt();
1134 < //         awaitTermination(t);
1135 < //         releaseWriteLock(lock);
1136 < //     }
1137 <
1138 < //     /**
1139 < //      * timed write-tryLock is interruptible
1140 < //      */
1141 < //     public void testWriteTryLock_Interruptible()      { testWriteTryLock_Interruptible(false); }
1142 < //     public void testWriteTryLock_Interruptible_fair() { testWriteTryLock_Interruptible(true); }
1143 < //     public void testWriteTryLock_Interruptible(boolean fair) {
1144 < //         final PublicReentrantReadWriteLock lock =
1145 < //             new PublicReentrantReadWriteLock(fair);
1146 < //         lock.writeLock().lock();
1147 < //         Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1148 < //             public void realRun() throws InterruptedException {
1149 < //                 lock.writeLock().tryLock(2 * LONG_DELAY_MS, MILLISECONDS);
1150 < //             }});
1151 <
1152 < //         waitForQueuedThread(lock, t);
1153 < //         t.interrupt();
1154 < //         awaitTermination(t);
1155 < //         releaseWriteLock(lock);
1156 < //     }
1157 <
1158 < //     /**
1159 < //      * read-lockInterruptibly is interruptible
1160 < //      */
1161 < //     public void testReadLockInterruptibly_Interruptible()      { testReadLockInterruptibly_Interruptible(false); }
1162 < //     public void testReadLockInterruptibly_Interruptible_fair() { testReadLockInterruptibly_Interruptible(true); }
1163 < //     public void testReadLockInterruptibly_Interruptible(boolean fair) {
1164 < //         final PublicReentrantReadWriteLock lock =
1165 < //             new PublicReentrantReadWriteLock(fair);
1166 < //         lock.writeLock().lock();
1167 < //         Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1168 < //             public void realRun() throws InterruptedException {
1169 < //                 lock.readLock().lockInterruptibly();
1170 < //             }});
1171 <
1172 < //         waitForQueuedThread(lock, t);
1173 < //         t.interrupt();
1174 < //         awaitTermination(t);
1175 < //         releaseWriteLock(lock);
1176 < //     }
1177 <
1178 < //     /**
1179 < //      * timed read-tryLock is interruptible
1180 < //      */
1181 < //     public void testReadTryLock_Interruptible()      { testReadTryLock_Interruptible(false); }
1182 < //     public void testReadTryLock_Interruptible_fair() { testReadTryLock_Interruptible(true); }
1183 < //     public void testReadTryLock_Interruptible(boolean fair) {
1184 < //         final PublicReentrantReadWriteLock lock =
1185 < //             new PublicReentrantReadWriteLock(fair);
1186 < //         lock.writeLock().lock();
1187 < //         Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1188 < //             public void realRun() throws InterruptedException {
1189 < //                 lock.readLock().tryLock(2 * LONG_DELAY_MS, MILLISECONDS);
1190 < //             }});
1191 <
1192 < //         waitForQueuedThread(lock, t);
1193 < //         t.interrupt();
1194 < //         awaitTermination(t);
1195 < //         releaseWriteLock(lock);
1196 < //     }
1197 <
1198 < //     /**
1199 < //      * write-tryLock on an unlocked lock succeeds
1200 < //      */
1201 < //     public void testWriteTryLock()      { testWriteTryLock(false); }
1202 < //     public void testWriteTryLock_fair() { testWriteTryLock(true); }
1203 < //     public void testWriteTryLock(boolean fair) {
1204 < //         final PublicReentrantReadWriteLock lock =
1205 < //             new PublicReentrantReadWriteLock(fair);
1206 < //         assertTrue(lock.writeLock().tryLock());
1207 < //         assertWriteLockedByMoi(lock);
1208 < //         assertTrue(lock.writeLock().tryLock());
1209 < //         assertWriteLockedByMoi(lock);
1210 < //         lock.writeLock().unlock();
1211 < //         releaseWriteLock(lock);
1212 < //     }
1213 <
1214 < //     /**
1215 < //      * write-tryLock fails if locked
1216 < //      */
1217 < //     public void testWriteTryLockWhenLocked()      { testWriteTryLockWhenLocked(false); }
1218 < //     public void testWriteTryLockWhenLocked_fair() { testWriteTryLockWhenLocked(true); }
1219 < //     public void testWriteTryLockWhenLocked(boolean fair) {
1220 < //         final PublicReentrantReadWriteLock lock =
1221 < //             new PublicReentrantReadWriteLock(fair);
1222 < //         lock.writeLock().lock();
1223 < //         Thread t = newStartedThread(new CheckedRunnable() {
1224 < //             public void realRun() {
1225 < //                 assertFalse(lock.writeLock().tryLock());
1226 < //             }});
1227 <
1228 < //         awaitTermination(t);
1229 < //         releaseWriteLock(lock);
1230 < //     }
1231 <
1232 < //     /**
1233 < //      * read-tryLock fails if locked
1234 < //      */
1235 < //     public void testReadTryLockWhenLocked()      { testReadTryLockWhenLocked(false); }
1236 < //     public void testReadTryLockWhenLocked_fair() { testReadTryLockWhenLocked(true); }
1237 < //     public void testReadTryLockWhenLocked(boolean fair) {
1238 < //         final PublicReentrantReadWriteLock lock =
1239 < //             new PublicReentrantReadWriteLock(fair);
1240 < //         lock.writeLock().lock();
1241 < //         Thread t = newStartedThread(new CheckedRunnable() {
1242 < //             public void realRun() {
1243 < //                 assertFalse(lock.readLock().tryLock());
1244 < //             }});
1245 <
1246 < //         awaitTermination(t);
1247 < //         releaseWriteLock(lock);
1248 < //     }
1249 <
1250 < //     /**
1251 < //      * Multiple threads can hold a read lock when not write-locked
1252 < //      */
1253 < //     public void testMultipleReadLocks()      { testMultipleReadLocks(false); }
1254 < //     public void testMultipleReadLocks_fair() { testMultipleReadLocks(true); }
1255 < //     public void testMultipleReadLocks(boolean fair) {
1256 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1257 < //         lock.readLock().lock();
1258 < //         Thread t = newStartedThread(new CheckedRunnable() {
1259 < //             public void realRun() throws InterruptedException {
1260 < //                 assertTrue(lock.readLock().tryLock());
1261 < //                 lock.readLock().unlock();
1262 < //                 assertTrue(lock.readLock().tryLock(LONG_DELAY_MS, MILLISECONDS));
1263 < //                 lock.readLock().unlock();
1264 < //                 lock.readLock().lock();
1265 < //                 lock.readLock().unlock();
1266 < //             }});
1267 <
1268 < //         awaitTermination(t);
1269 < //         lock.readLock().unlock();
1270 < //     }
1271 <
1272 < //     /**
1273 < //      * A writelock succeeds only after a reading thread unlocks
1274 < //      */
1275 < //     public void testWriteAfterReadLock()      { testWriteAfterReadLock(false); }
1276 < //     public void testWriteAfterReadLock_fair() { testWriteAfterReadLock(true); }
1277 < //     public void testWriteAfterReadLock(boolean fair) {
1278 < //         final PublicReentrantReadWriteLock lock =
1279 < //             new PublicReentrantReadWriteLock(fair);
1280 < //         lock.readLock().lock();
1281 < //         Thread t = newStartedThread(new CheckedRunnable() {
1282 < //             public void realRun() {
1283 < //                 assertEquals(1, lock.getReadLockCount());
1284 < //                 lock.writeLock().lock();
1285 < //                 assertEquals(0, lock.getReadLockCount());
1286 < //                 lock.writeLock().unlock();
1287 < //             }});
1288 < //         waitForQueuedThread(lock, t);
1289 < //         assertNotWriteLocked(lock);
1290 < //         assertEquals(1, lock.getReadLockCount());
1291 < //         lock.readLock().unlock();
1292 < //         assertEquals(0, lock.getReadLockCount());
1293 < //         awaitTermination(t);
1294 < //         assertNotWriteLocked(lock);
1295 < //     }
1296 <
1297 < //     /**
1298 < //      * A writelock succeeds only after reading threads unlock
1299 < //      */
1300 < //     public void testWriteAfterMultipleReadLocks()      { testWriteAfterMultipleReadLocks(false); }
1301 < //     public void testWriteAfterMultipleReadLocks_fair() { testWriteAfterMultipleReadLocks(true); }
1302 < //     public void testWriteAfterMultipleReadLocks(boolean fair) {
1303 < //         final PublicReentrantReadWriteLock lock =
1304 < //             new PublicReentrantReadWriteLock(fair);
1305 < //         lock.readLock().lock();
1306 < //         lock.readLock().lock();
1307 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
1308 < //             public void realRun() {
1309 < //                 lock.readLock().lock();
1310 < //                 assertEquals(3, lock.getReadLockCount());
1311 < //                 lock.readLock().unlock();
1312 < //             }});
1313 < //         awaitTermination(t1);
1314 <
1315 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
1316 < //             public void realRun() {
1317 < //                 assertEquals(2, lock.getReadLockCount());
1318 < //                 lock.writeLock().lock();
1319 < //                 assertEquals(0, lock.getReadLockCount());
1320 < //                 lock.writeLock().unlock();
1321 < //             }});
1322 < //         waitForQueuedThread(lock, t2);
1323 < //         assertNotWriteLocked(lock);
1324 < //         assertEquals(2, lock.getReadLockCount());
1325 < //         lock.readLock().unlock();
1326 < //         lock.readLock().unlock();
1327 < //         assertEquals(0, lock.getReadLockCount());
1328 < //         awaitTermination(t2);
1329 < //         assertNotWriteLocked(lock);
1330 < //     }
1331 <
1332 < //     /**
1333 < //      * A thread that tries to acquire a fair read lock (non-reentrantly)
1334 < //      * will block if there is a waiting writer thread
1335 < //      */
1336 < //     public void testReaderWriterReaderFairFifo() {
1337 < //         final PublicReentrantReadWriteLock lock =
1338 < //             new PublicReentrantReadWriteLock(true);
1339 < //         final AtomicBoolean t1GotLock = new AtomicBoolean(false);
1340 <
1341 < //         lock.readLock().lock();
1342 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
1343 < //             public void realRun() {
1344 < //                 assertEquals(1, lock.getReadLockCount());
1345 < //                 lock.writeLock().lock();
1346 < //                 assertEquals(0, lock.getReadLockCount());
1347 < //                 t1GotLock.set(true);
1348 < //                 lock.writeLock().unlock();
1349 < //             }});
1350 < //         waitForQueuedThread(lock, t1);
1351 <
1352 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
1353 < //             public void realRun() {
1354 < //                 assertEquals(1, lock.getReadLockCount());
1355 < //                 lock.readLock().lock();
1356 < //                 assertEquals(1, lock.getReadLockCount());
1357 < //                 assertTrue(t1GotLock.get());
1358 < //                 lock.readLock().unlock();
1359 < //             }});
1360 < //         waitForQueuedThread(lock, t2);
1361 < //         assertTrue(t1.isAlive());
1362 < //         assertNotWriteLocked(lock);
1363 < //         assertEquals(1, lock.getReadLockCount());
1364 < //         lock.readLock().unlock();
1365 < //         awaitTermination(t1);
1366 < //         awaitTermination(t2);
1367 < //         assertNotWriteLocked(lock);
1368 < //     }
1369 <
1370 < //     /**
1371 < //      * Readlocks succeed only after a writing thread unlocks
1372 < //      */
1373 < //     public void testReadAfterWriteLock()      { testReadAfterWriteLock(false); }
1374 < //     public void testReadAfterWriteLock_fair() { testReadAfterWriteLock(true); }
1375 < //     public void testReadAfterWriteLock(boolean fair) {
1376 < //         final PublicReentrantReadWriteLock lock =
1377 < //             new PublicReentrantReadWriteLock(fair);
1378 < //         lock.writeLock().lock();
1379 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
1380 < //             public void realRun() {
1381 < //                 lock.readLock().lock();
1382 < //                 lock.readLock().unlock();
1383 < //             }});
1384 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
1385 < //             public void realRun() {
1386 < //                 lock.readLock().lock();
1387 < //                 lock.readLock().unlock();
572 < //             }});
573 <
574 < //         waitForQueuedThread(lock, t1);
575 < //         waitForQueuedThread(lock, t2);
576 < //         releaseWriteLock(lock);
577 < //         awaitTermination(t1);
578 < //         awaitTermination(t2);
579 < //     }
580 <
581 < //     /**
582 < //      * Read trylock succeeds if write locked by current thread
583 < //      */
584 < //     public void testReadHoldingWriteLock()      { testReadHoldingWriteLock(false); }
585 < //     public void testReadHoldingWriteLock_fair() { testReadHoldingWriteLock(true); }
586 < //     public void testReadHoldingWriteLock(boolean fair) {
587 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
588 < //         lock.writeLock().lock();
589 < //         assertTrue(lock.readLock().tryLock());
590 < //         lock.readLock().unlock();
591 < //         lock.writeLock().unlock();
592 < //     }
593 <
594 < //     /**
595 < //      * Read trylock succeeds (barging) even in the presence of waiting
596 < //      * readers and/or writers
597 < //      */
598 < //     public void testReadTryLockBarging()      { testReadTryLockBarging(false); }
599 < //     public void testReadTryLockBarging_fair() { testReadTryLockBarging(true); }
600 < //     public void testReadTryLockBarging(boolean fair) {
601 < //         final PublicReentrantReadWriteLock lock =
602 < //             new PublicReentrantReadWriteLock(fair);
603 < //         lock.readLock().lock();
604 <
605 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
606 < //             public void realRun() {
607 < //                 lock.writeLock().lock();
608 < //                 lock.writeLock().unlock();
609 < //             }});
610 <
611 < //         waitForQueuedThread(lock, t1);
612 <
613 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
614 < //             public void realRun() {
615 < //                 lock.readLock().lock();
616 < //                 lock.readLock().unlock();
617 < //             }});
618 <
619 < //         if (fair)
620 < //             waitForQueuedThread(lock, t2);
621 <
622 < //         Thread t3 = newStartedThread(new CheckedRunnable() {
623 < //             public void realRun() {
624 < //                 lock.readLock().tryLock();
625 < //                 lock.readLock().unlock();
626 < //             }});
627 <
628 < //         assertTrue(lock.getReadLockCount() > 0);
629 < //         awaitTermination(t3);
630 < //         assertTrue(t1.isAlive());
631 < //         if (fair) assertTrue(t2.isAlive());
632 < //         lock.readLock().unlock();
633 < //         awaitTermination(t1);
634 < //         awaitTermination(t2);
635 < //     }
636 <
637 < //     /**
638 < //      * Read lock succeeds if write locked by current thread even if
639 < //      * other threads are waiting for readlock
640 < //      */
641 < //     public void testReadHoldingWriteLock2()      { testReadHoldingWriteLock2(false); }
642 < //     public void testReadHoldingWriteLock2_fair() { testReadHoldingWriteLock2(true); }
643 < //     public void testReadHoldingWriteLock2(boolean fair) {
644 < //         final PublicReentrantReadWriteLock lock =
645 < //             new PublicReentrantReadWriteLock(fair);
646 < //         lock.writeLock().lock();
647 < //         lock.readLock().lock();
648 < //         lock.readLock().unlock();
649 <
650 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
651 < //             public void realRun() {
652 < //                 lock.readLock().lock();
653 < //                 lock.readLock().unlock();
654 < //             }});
655 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
656 < //             public void realRun() {
657 < //                 lock.readLock().lock();
658 < //                 lock.readLock().unlock();
659 < //             }});
660 <
661 < //         waitForQueuedThread(lock, t1);
662 < //         waitForQueuedThread(lock, t2);
663 < //         assertWriteLockedByMoi(lock);
664 < //         lock.readLock().lock();
665 < //         lock.readLock().unlock();
666 < //         releaseWriteLock(lock);
667 < //         awaitTermination(t1);
668 < //         awaitTermination(t2);
669 < //     }
670 <
671 < //     /**
672 < //      * Read lock succeeds if write locked by current thread even if
673 < //      * other threads are waiting for writelock
674 < //      */
675 < //     public void testReadHoldingWriteLock3()      { testReadHoldingWriteLock3(false); }
676 < //     public void testReadHoldingWriteLock3_fair() { testReadHoldingWriteLock3(true); }
677 < //     public void testReadHoldingWriteLock3(boolean fair) {
678 < //         final PublicReentrantReadWriteLock lock =
679 < //             new PublicReentrantReadWriteLock(fair);
680 < //         lock.writeLock().lock();
681 < //         lock.readLock().lock();
682 < //         lock.readLock().unlock();
683 <
684 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
685 < //             public void realRun() {
686 < //                 lock.writeLock().lock();
687 < //                 lock.writeLock().unlock();
688 < //             }});
689 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
690 < //             public void realRun() {
691 < //                 lock.writeLock().lock();
692 < //                 lock.writeLock().unlock();
693 < //             }});
694 <
695 < //         waitForQueuedThread(lock, t1);
696 < //         waitForQueuedThread(lock, t2);
697 < //         assertWriteLockedByMoi(lock);
698 < //         lock.readLock().lock();
699 < //         lock.readLock().unlock();
700 < //         assertWriteLockedByMoi(lock);
701 < //         lock.writeLock().unlock();
702 < //         awaitTermination(t1);
703 < //         awaitTermination(t2);
704 < //     }
705 <
706 < //     /**
707 < //      * Write lock succeeds if write locked by current thread even if
708 < //      * other threads are waiting for writelock
709 < //      */
710 < //     public void testWriteHoldingWriteLock4()      { testWriteHoldingWriteLock4(false); }
711 < //     public void testWriteHoldingWriteLock4_fair() { testWriteHoldingWriteLock4(true); }
712 < //     public void testWriteHoldingWriteLock4(boolean fair) {
713 < //         final PublicReentrantReadWriteLock lock =
714 < //             new PublicReentrantReadWriteLock(fair);
715 < //         lock.writeLock().lock();
716 < //         lock.writeLock().lock();
717 < //         lock.writeLock().unlock();
718 <
719 < //         Thread t1 = newStartedThread(new CheckedRunnable() {
720 < //             public void realRun() {
721 < //                 lock.writeLock().lock();
722 < //                 lock.writeLock().unlock();
723 < //             }});
724 < //         Thread t2 = newStartedThread(new CheckedRunnable() {
725 < //             public void realRun() {
726 < //                 lock.writeLock().lock();
727 < //                 lock.writeLock().unlock();
728 < //             }});
729 <
730 < //         waitForQueuedThread(lock, t1);
731 < //         waitForQueuedThread(lock, t2);
732 < //         assertWriteLockedByMoi(lock);
733 < //         assertEquals(1, lock.getWriteHoldCount());
734 < //         lock.writeLock().lock();
735 < //         assertWriteLockedByMoi(lock);
736 < //         assertEquals(2, lock.getWriteHoldCount());
737 < //         lock.writeLock().unlock();
738 < //         assertWriteLockedByMoi(lock);
739 < //         assertEquals(1, lock.getWriteHoldCount());
740 < //         lock.writeLock().unlock();
741 < //         awaitTermination(t1);
742 < //         awaitTermination(t2);
743 < //     }
744 <
745 < //     /**
746 < //      * Read tryLock succeeds if readlocked but not writelocked
747 < //      */
748 < //     public void testTryLockWhenReadLocked()      { testTryLockWhenReadLocked(false); }
749 < //     public void testTryLockWhenReadLocked_fair() { testTryLockWhenReadLocked(true); }
750 < //     public void testTryLockWhenReadLocked(boolean fair) {
751 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
752 < //         lock.readLock().lock();
753 < //         Thread t = newStartedThread(new CheckedRunnable() {
754 < //             public void realRun() {
755 < //                 assertTrue(lock.readLock().tryLock());
756 < //                 lock.readLock().unlock();
757 < //             }});
758 <
759 < //         awaitTermination(t);
760 < //         lock.readLock().unlock();
761 < //     }
762 <
763 < //     /**
764 < //      * write tryLock fails when readlocked
765 < //      */
766 < //     public void testWriteTryLockWhenReadLocked()      { testWriteTryLockWhenReadLocked(false); }
767 < //     public void testWriteTryLockWhenReadLocked_fair() { testWriteTryLockWhenReadLocked(true); }
768 < //     public void testWriteTryLockWhenReadLocked(boolean fair) {
769 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
770 < //         lock.readLock().lock();
771 < //         Thread t = newStartedThread(new CheckedRunnable() {
772 < //             public void realRun() {
773 < //                 assertFalse(lock.writeLock().tryLock());
774 < //             }});
775 <
776 < //         awaitTermination(t);
777 < //         lock.readLock().unlock();
778 < //     }
779 <
780 < //     /**
781 < //      * write timed tryLock times out if locked
782 < //      */
783 < //     public void testWriteTryLock_Timeout()      { testWriteTryLock_Timeout(false); }
784 < //     public void testWriteTryLock_Timeout_fair() { testWriteTryLock_Timeout(true); }
785 < //     public void testWriteTryLock_Timeout(boolean fair) {
786 < //         final PublicReentrantReadWriteLock lock =
787 < //             new PublicReentrantReadWriteLock(fair);
788 < //         lock.writeLock().lock();
789 < //         Thread t = newStartedThread(new CheckedRunnable() {
790 < //             public void realRun() throws InterruptedException {
791 < //                 long startTime = System.nanoTime();
792 < //                 long timeoutMillis = 10;
793 < //                 assertFalse(lock.writeLock().tryLock(timeoutMillis, MILLISECONDS));
794 < //                 assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
795 < //             }});
796 <
797 < //         awaitTermination(t);
798 < //         releaseWriteLock(lock);
799 < //     }
800 <
801 < //     /**
802 < //      * read timed tryLock times out if write-locked
803 < //      */
804 < //     public void testReadTryLock_Timeout()      { testReadTryLock_Timeout(false); }
805 < //     public void testReadTryLock_Timeout_fair() { testReadTryLock_Timeout(true); }
806 < //     public void testReadTryLock_Timeout(boolean fair) {
807 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
808 < //         lock.writeLock().lock();
809 < //         Thread t = newStartedThread(new CheckedRunnable() {
810 < //             public void realRun() throws InterruptedException {
811 < //                 long startTime = System.nanoTime();
812 < //                 long timeoutMillis = 10;
813 < //                 assertFalse(lock.readLock().tryLock(timeoutMillis, MILLISECONDS));
814 < //                 assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
815 < //             }});
816 <
817 < //         awaitTermination(t);
818 < //         assertTrue(lock.writeLock().isHeldByCurrentThread());
819 < //         lock.writeLock().unlock();
820 < //     }
821 <
822 < //     /**
823 < //      * write lockInterruptibly succeeds if unlocked, else is interruptible
824 < //      */
825 < //     public void testWriteLockInterruptibly()      { testWriteLockInterruptibly(false); }
826 < //     public void testWriteLockInterruptibly_fair() { testWriteLockInterruptibly(true); }
827 < //     public void testWriteLockInterruptibly(boolean fair) {
828 < //         final PublicReentrantReadWriteLock lock =
829 < //             new PublicReentrantReadWriteLock(fair);
830 < //         try {
831 < //             lock.writeLock().lockInterruptibly();
832 < //         } catch (InterruptedException ie) {
833 < //             threadUnexpectedException(ie);
834 < //         }
835 < //         Thread t = newStartedThread(new CheckedInterruptedRunnable() {
836 < //             public void realRun() throws InterruptedException {
837 < //                 lock.writeLock().lockInterruptibly();
838 < //             }});
839 <
840 < //         waitForQueuedThread(lock, t);
841 < //         t.interrupt();
842 < //         assertTrue(lock.writeLock().isHeldByCurrentThread());
843 < //         awaitTermination(t);
844 < //         releaseWriteLock(lock);
845 < //     }
846 <
847 < //     /**
848 < //      * read lockInterruptibly succeeds if lock free else is interruptible
849 < //      */
850 < //     public void testReadLockInterruptibly()      { testReadLockInterruptibly(false); }
851 < //     public void testReadLockInterruptibly_fair() { testReadLockInterruptibly(true); }
852 < //     public void testReadLockInterruptibly(boolean fair) {
853 < //         final PublicReentrantReadWriteLock lock =
854 < //             new PublicReentrantReadWriteLock(fair);
855 < //         try {
856 < //             lock.readLock().lockInterruptibly();
857 < //             lock.readLock().unlock();
858 < //             lock.writeLock().lockInterruptibly();
859 < //         } catch (InterruptedException ie) {
860 < //             threadUnexpectedException(ie);
861 < //         }
862 < //         Thread t = newStartedThread(new CheckedInterruptedRunnable() {
863 < //             public void realRun() throws InterruptedException {
864 < //                 lock.readLock().lockInterruptibly();
865 < //             }});
866 <
867 < //         waitForQueuedThread(lock, t);
868 < //         t.interrupt();
869 < //         awaitTermination(t);
870 < //         releaseWriteLock(lock);
871 < //     }
872 <
873 < //     /**
874 < //      * Calling await without holding lock throws IllegalMonitorStateException
875 < //      */
876 < //     public void testAwait_IMSE()      { testAwait_IMSE(false); }
877 < //     public void testAwait_IMSE_fair() { testAwait_IMSE(true); }
878 < //     public void testAwait_IMSE(boolean fair) {
879 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
880 < //         final Condition c = lock.writeLock().newCondition();
881 < //         for (AwaitMethod awaitMethod : AwaitMethod.values()) {
882 < //             long startTime = System.nanoTime();
883 < //             try {
884 < //                 await(c, awaitMethod);
885 < //                 shouldThrow();
886 < //             } catch (IllegalMonitorStateException success) {
887 < //             } catch (InterruptedException e) { threadUnexpectedException(e); }
888 < //             assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
889 < //         }
890 < //     }
891 <
892 < //     /**
893 < //      * Calling signal without holding lock throws IllegalMonitorStateException
894 < //      */
895 < //     public void testSignal_IMSE()      { testSignal_IMSE(false); }
896 < //     public void testSignal_IMSE_fair() { testSignal_IMSE(true); }
897 < //     public void testSignal_IMSE(boolean fair) {
898 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
899 < //         final Condition c = lock.writeLock().newCondition();
900 < //         try {
901 < //             c.signal();
902 < //             shouldThrow();
903 < //         } catch (IllegalMonitorStateException success) {}
904 < //     }
905 <
906 < //     /**
907 < //      * Calling signalAll without holding lock throws IllegalMonitorStateException
908 < //      */
909 < //     public void testSignalAll_IMSE()      { testSignalAll_IMSE(false); }
910 < //     public void testSignalAll_IMSE_fair() { testSignalAll_IMSE(true); }
911 < //     public void testSignalAll_IMSE(boolean fair) {
912 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
913 < //         final Condition c = lock.writeLock().newCondition();
914 < //         try {
915 < //             c.signalAll();
916 < //             shouldThrow();
917 < //         } catch (IllegalMonitorStateException success) {}
918 < //     }
919 <
920 < //     /**
921 < //      * awaitNanos without a signal times out
922 < //      */
923 < //     public void testAwaitNanos_Timeout()      { testAwaitNanos_Timeout(false); }
924 < //     public void testAwaitNanos_Timeout_fair() { testAwaitNanos_Timeout(true); }
925 < //     public void testAwaitNanos_Timeout(boolean fair) {
926 < //         try {
927 < //             final ReentrantReadWriteLock lock =
928 < //                 new ReentrantReadWriteLock(fair);
929 < //             final Condition c = lock.writeLock().newCondition();
930 < //             lock.writeLock().lock();
931 < //             long startTime = System.nanoTime();
932 < //             long timeoutMillis = 10;
933 < //             long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
934 < //             long nanosRemaining = c.awaitNanos(timeoutNanos);
935 < //             assertTrue(nanosRemaining <= 0);
936 < //             assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
937 < //             lock.writeLock().unlock();
938 < //         } catch (InterruptedException e) {
939 < //             threadUnexpectedException(e);
940 < //         }
941 < //     }
942 <
943 < //     /**
944 < //      * timed await without a signal times out
945 < //      */
946 < //     public void testAwait_Timeout()      { testAwait_Timeout(false); }
947 < //     public void testAwait_Timeout_fair() { testAwait_Timeout(true); }
948 < //     public void testAwait_Timeout(boolean fair) {
949 < //         try {
950 < //             final ReentrantReadWriteLock lock =
951 < //                 new ReentrantReadWriteLock(fair);
952 < //             final Condition c = lock.writeLock().newCondition();
953 < //             lock.writeLock().lock();
954 < //             long startTime = System.nanoTime();
955 < //             long timeoutMillis = 10;
956 < //             assertFalse(c.await(timeoutMillis, MILLISECONDS));
957 < //             assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
958 < //             lock.writeLock().unlock();
959 < //         } catch (InterruptedException e) {
960 < //             threadUnexpectedException(e);
961 < //         }
962 < //     }
963 <
964 < //     /**
965 < //      * awaitUntil without a signal times out
966 < //      */
967 < //     public void testAwaitUntil_Timeout()      { testAwaitUntil_Timeout(false); }
968 < //     public void testAwaitUntil_Timeout_fair() { testAwaitUntil_Timeout(true); }
969 < //     public void testAwaitUntil_Timeout(boolean fair) {
970 < //         try {
971 < //             final ReentrantReadWriteLock lock =
972 < //                 new ReentrantReadWriteLock(fair);
973 < //             final Condition c = lock.writeLock().newCondition();
974 < //             lock.writeLock().lock();
975 < //             long startTime = System.nanoTime();
976 < //             long timeoutMillis = 10;
977 < //             java.util.Date d = new java.util.Date();
978 < //             assertFalse(c.awaitUntil(new java.util.Date(d.getTime() + timeoutMillis)));
979 < //             assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
980 < //             lock.writeLock().unlock();
981 < //         } catch (InterruptedException e) {
982 < //             threadUnexpectedException(e);
983 < //         }
984 < //     }
985 <
986 < //     /**
987 < //      * await returns when signalled
988 < //      */
989 < //     public void testAwait()      { testAwait(false); }
990 < //     public void testAwait_fair() { testAwait(true); }
991 < //     public void testAwait(boolean fair) {
992 < //         final PublicReentrantReadWriteLock lock =
993 < //             new PublicReentrantReadWriteLock(fair);
994 < //         final Condition c = lock.writeLock().newCondition();
995 < //         final CountDownLatch locked = new CountDownLatch(1);
996 < //         Thread t = newStartedThread(new CheckedRunnable() {
997 < //             public void realRun() throws InterruptedException {
998 < //                 lock.writeLock().lock();
999 < //                 locked.countDown();
1000 < //                 c.await();
1001 < //                 lock.writeLock().unlock();
1002 < //             }});
1003 <
1004 < //         await(locked);
1005 < //         lock.writeLock().lock();
1006 < //         assertHasWaiters(lock, c, t);
1007 < //         c.signal();
1008 < //         assertHasNoWaiters(lock, c);
1009 < //         assertTrue(t.isAlive());
1010 < //         lock.writeLock().unlock();
1011 < //         awaitTermination(t);
1012 < //     }
1013 <
1014 < //     /**
1015 < //      * awaitUninterruptibly is uninterruptible
1016 < //      */
1017 < //     public void testAwaitUninterruptibly()      { testAwaitUninterruptibly(false); }
1018 < //     public void testAwaitUninterruptibly_fair() { testAwaitUninterruptibly(true); }
1019 < //     public void testAwaitUninterruptibly(boolean fair) {
1020 < //         final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
1021 < //         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 < //     }
849 >    /**
850 >     * tryConvertToWriteLock succeeds if lock available; fails if multiply read locked
851 >     */
852 >    public void testTryConvertToWriteLock() throws InterruptedException {
853 >        StampedLock lock = new StampedLock();
854 >        long s, p;
855 >
856 >        assertEquals(0L, lock.tryConvertToWriteLock(0L));
857 >
858 >        assertTrue((s = lock.tryOptimisticRead()) != 0L);
859 >        assertTrue((p = lock.tryConvertToWriteLock(s)) != 0L);
860 >        assertTrue(lock.isWriteLocked());
861 >        lock.unlockWrite(p);
862 >
863 >        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
864 >            for (Function<StampedLock, Long> writeLocker : writeLockers()) {
865 >                s = assertValid(lock, writeLocker.apply(lock));
866 >                assertEquals(s, lock.tryConvertToWriteLock(s));
867 >                assertTrue(lock.validate(s));
868 >                assertTrue(lock.isWriteLocked());
869 >                writeUnlocker.accept(lock, s);
870 >            }
871 >
872 >            for (Function<StampedLock, Long> readLocker : readLockers()) {
873 >                s = assertValid(lock, readLocker.apply(lock));
874 >                p = assertValid(lock, lock.tryConvertToWriteLock(s));
875 >                assertFalse(lock.validate(s));
876 >                assertTrue(lock.validate(p));
877 >                assertTrue(lock.isWriteLocked());
878 >                writeUnlocker.accept(lock, p);
879 >            }
880 >        }
881 >
882 >        // failure if multiply read locked
883 >        for (Function<StampedLock, Long> readLocker : readLockers()) {
884 >            s = assertValid(lock, readLocker.apply(lock));
885 >            p = assertValid(lock, readLocker.apply(lock));
886 >            assertEquals(0L, lock.tryConvertToWriteLock(s));
887 >            assertTrue(lock.validate(s));
888 >            assertTrue(lock.validate(p));
889 >            assertEquals(2, lock.getReadLockCount());
890 >            lock.unlock(p);
891 >            lock.unlock(s);
892 >            assertUnlocked(lock);
893 >        }
894 >    }
895 >
896 >    /**
897 >     * asWriteLock can be locked and unlocked
898 >     */
899 >    public void testAsWriteLock() throws Throwable {
900 >        StampedLock sl = new StampedLock();
901 >        Lock lock = sl.asWriteLock();
902 >        for (Action locker : lockLockers(lock)) {
903 >            locker.run();
904 >            assertTrue(sl.isWriteLocked());
905 >            assertFalse(sl.isReadLocked());
906 >            assertFalse(lock.tryLock());
907 >            lock.unlock();
908 >            assertUnlocked(sl);
909 >        }
910 >    }
911 >
912 >    /**
913 >     * asReadLock can be locked and unlocked
914 >     */
915 >    public void testAsReadLock() throws Throwable {
916 >        StampedLock sl = new StampedLock();
917 >        Lock lock = sl.asReadLock();
918 >        for (Action locker : lockLockers(lock)) {
919 >            locker.run();
920 >            assertTrue(sl.isReadLocked());
921 >            assertFalse(sl.isWriteLocked());
922 >            assertEquals(1, sl.getReadLockCount());
923 >            locker.run();
924 >            assertTrue(sl.isReadLocked());
925 >            assertEquals(2, sl.getReadLockCount());
926 >            lock.unlock();
927 >            lock.unlock();
928 >            assertUnlocked(sl);
929 >        }
930 >    }
931 >
932 >    /**
933 >     * asReadWriteLock.writeLock can be locked and unlocked
934 >     */
935 >    public void testAsReadWriteLockWriteLock() throws Throwable {
936 >        StampedLock sl = new StampedLock();
937 >        Lock lock = sl.asReadWriteLock().writeLock();
938 >        for (Action locker : lockLockers(lock)) {
939 >            locker.run();
940 >            assertTrue(sl.isWriteLocked());
941 >            assertFalse(sl.isReadLocked());
942 >            assertFalse(lock.tryLock());
943 >            lock.unlock();
944 >            assertUnlocked(sl);
945 >        }
946 >    }
947 >
948 >    /**
949 >     * asReadWriteLock.readLock can be locked and unlocked
950 >     */
951 >    public void testAsReadWriteLockReadLock() throws Throwable {
952 >        StampedLock sl = new StampedLock();
953 >        Lock lock = sl.asReadWriteLock().readLock();
954 >        for (Action locker : lockLockers(lock)) {
955 >            locker.run();
956 >            assertTrue(sl.isReadLocked());
957 >            assertFalse(sl.isWriteLocked());
958 >            assertEquals(1, sl.getReadLockCount());
959 >            locker.run();
960 >            assertTrue(sl.isReadLocked());
961 >            assertEquals(2, sl.getReadLockCount());
962 >            lock.unlock();
963 >            lock.unlock();
964 >            assertUnlocked(sl);
965 >        }
966 >    }
967 >
968 >    /**
969 >     * Lock.newCondition throws UnsupportedOperationException
970 >     */
971 >    public void testLockViewsDoNotSupportConditions() {
972 >        StampedLock sl = new StampedLock();
973 >        assertThrows(UnsupportedOperationException.class,
974 >                     () -> sl.asWriteLock().newCondition(),
975 >                     () -> sl.asReadLock().newCondition(),
976 >                     () -> sl.asReadWriteLock().writeLock().newCondition(),
977 >                     () -> sl.asReadWriteLock().readLock().newCondition());
978 >    }
979 >
980 >    /**
981 >     * Passing optimistic read stamps to unlock operations result in
982 >     * IllegalMonitorStateException
983 >     */
984 >    public void testCannotUnlockOptimisticReadStamps() {
985 >        {
986 >            StampedLock sl = new StampedLock();
987 >            long stamp = assertValid(sl, sl.tryOptimisticRead());
988 >            assertThrows(IllegalMonitorStateException.class,
989 >                () -> sl.unlockRead(stamp));
990 >        }
991 >        {
992 >            StampedLock sl = new StampedLock();
993 >            long stamp = sl.tryOptimisticRead();
994 >            assertThrows(IllegalMonitorStateException.class,
995 >                () -> sl.unlock(stamp));
996 >        }
997 >
998 >        {
999 >            StampedLock sl = new StampedLock();
1000 >            long stamp = sl.tryOptimisticRead();
1001 >            sl.writeLock();
1002 >            assertThrows(IllegalMonitorStateException.class,
1003 >                () -> sl.unlock(stamp));
1004 >        }
1005 >        {
1006 >            StampedLock sl = new StampedLock();
1007 >            sl.readLock();
1008 >            long stamp = assertValid(sl, sl.tryOptimisticRead());
1009 >            assertThrows(IllegalMonitorStateException.class,
1010 >                () -> sl.unlockRead(stamp));
1011 >        }
1012 >        {
1013 >            StampedLock sl = new StampedLock();
1014 >            sl.readLock();
1015 >            long stamp = assertValid(sl, sl.tryOptimisticRead());
1016 >            assertThrows(IllegalMonitorStateException.class,
1017 >                () -> sl.unlock(stamp));
1018 >        }
1019 >
1020 >        {
1021 >            StampedLock sl = new StampedLock();
1022 >            long stamp = sl.tryConvertToOptimisticRead(sl.writeLock());
1023 >            assertValid(sl, stamp);
1024 >            sl.writeLock();
1025 >            assertThrows(IllegalMonitorStateException.class,
1026 >                () -> sl.unlockWrite(stamp));
1027 >        }
1028 >        {
1029 >            StampedLock sl = new StampedLock();
1030 >            long stamp = sl.tryConvertToOptimisticRead(sl.writeLock());
1031 >            sl.writeLock();
1032 >            assertThrows(IllegalMonitorStateException.class,
1033 >                () -> sl.unlock(stamp));
1034 >        }
1035 >        {
1036 >            StampedLock sl = new StampedLock();
1037 >            long stamp = sl.tryConvertToOptimisticRead(sl.writeLock());
1038 >            sl.readLock();
1039 >            assertThrows(IllegalMonitorStateException.class,
1040 >                () -> sl.unlockRead(stamp));
1041 >        }
1042 >        {
1043 >            StampedLock sl = new StampedLock();
1044 >            long stamp = sl.tryConvertToOptimisticRead(sl.writeLock());
1045 >            sl.readLock();
1046 >            assertThrows(IllegalMonitorStateException.class,
1047 >                () -> sl.unlock(stamp));
1048 >        }
1049 >
1050 >        {
1051 >            StampedLock sl = new StampedLock();
1052 >            long stamp = sl.tryConvertToOptimisticRead(sl.readLock());
1053 >            assertValid(sl, stamp);
1054 >            sl.writeLock();
1055 >            assertThrows(IllegalMonitorStateException.class,
1056 >                () -> sl.unlockWrite(stamp));
1057 >            }
1058 >        {
1059 >            StampedLock sl = new StampedLock();
1060 >            long stamp = sl.tryConvertToOptimisticRead(sl.readLock());
1061 >            sl.writeLock();
1062 >            assertThrows(IllegalMonitorStateException.class,
1063 >                () -> sl.unlock(stamp));
1064 >        }
1065 >        {
1066 >            StampedLock sl = new StampedLock();
1067 >            long stamp = sl.tryConvertToOptimisticRead(sl.readLock());
1068 >            sl.readLock();
1069 >            assertThrows(IllegalMonitorStateException.class,
1070 >                () -> sl.unlockRead(stamp));
1071 >        }
1072 >        {
1073 >            StampedLock sl = new StampedLock();
1074 >            sl.readLock();
1075 >            long stamp = sl.tryConvertToOptimisticRead(sl.readLock());
1076 >            assertValid(sl, stamp);
1077 >            sl.readLock();
1078 >            assertThrows(IllegalMonitorStateException.class,
1079 >                () -> sl.unlockRead(stamp));
1080 >        }
1081 >        {
1082 >            StampedLock sl = new StampedLock();
1083 >            long stamp = sl.tryConvertToOptimisticRead(sl.readLock());
1084 >            sl.readLock();
1085 >            assertThrows(IllegalMonitorStateException.class,
1086 >                () -> sl.unlock(stamp));
1087 >        }
1088 >        {
1089 >            StampedLock sl = new StampedLock();
1090 >            sl.readLock();
1091 >            long stamp = sl.tryConvertToOptimisticRead(sl.readLock());
1092 >            sl.readLock();
1093 >            assertThrows(IllegalMonitorStateException.class,
1094 >                () -> sl.unlock(stamp));
1095 >        }
1096 >    }
1097 >
1098 >    static long writeLockInterruptiblyUninterrupted(StampedLock sl) {
1099 >        try { return sl.writeLockInterruptibly(); }
1100 >        catch (InterruptedException ex) { throw new AssertionError(ex); }
1101 >    }
1102 >
1103 >    static long tryWriteLockUninterrupted(StampedLock sl, long time, TimeUnit unit) {
1104 >        try { return sl.tryWriteLock(time, unit); }
1105 >        catch (InterruptedException ex) { throw new AssertionError(ex); }
1106 >    }
1107 >
1108 >    static long readLockInterruptiblyUninterrupted(StampedLock sl) {
1109 >        try { return sl.readLockInterruptibly(); }
1110 >        catch (InterruptedException ex) { throw new AssertionError(ex); }
1111 >    }
1112 >
1113 >    static long tryReadLockUninterrupted(StampedLock sl, long time, TimeUnit unit) {
1114 >        try { return sl.tryReadLock(time, unit); }
1115 >        catch (InterruptedException ex) { throw new AssertionError(ex); }
1116 >    }
1117 >
1118 >    /**
1119 >     * Invalid stamps result in IllegalMonitorStateException
1120 >     */
1121 >    public void testInvalidStampsThrowIllegalMonitorStateException() {
1122 >        final StampedLock sl = new StampedLock();
1123 >
1124 >        assertThrows(IllegalMonitorStateException.class,
1125 >                     () -> sl.unlockWrite(0L),
1126 >                     () -> sl.unlockRead(0L),
1127 >                     () -> sl.unlock(0L));
1128 >
1129 >        final long optimisticStamp = sl.tryOptimisticRead();
1130 >        final long readStamp = sl.readLock();
1131 >        sl.unlockRead(readStamp);
1132 >        final long writeStamp = sl.writeLock();
1133 >        sl.unlockWrite(writeStamp);
1134 >        assertTrue(optimisticStamp != 0L && readStamp != 0L && writeStamp != 0L);
1135 >        final long[] noLongerValidStamps = { optimisticStamp, readStamp, writeStamp };
1136 >        final Runnable assertNoLongerValidStampsThrow = () -> {
1137 >            for (long noLongerValidStamp : noLongerValidStamps)
1138 >                assertThrows(IllegalMonitorStateException.class,
1139 >                             () -> sl.unlockWrite(noLongerValidStamp),
1140 >                             () -> sl.unlockRead(noLongerValidStamp),
1141 >                             () -> sl.unlock(noLongerValidStamp));
1142 >        };
1143 >        assertNoLongerValidStampsThrow.run();
1144 >
1145 >        for (Function<StampedLock, Long> readLocker : readLockers())
1146 >        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
1147 >            final long stamp = readLocker.apply(sl);
1148 >            assertValid(sl, stamp);
1149 >            assertNoLongerValidStampsThrow.run();
1150 >            assertThrows(IllegalMonitorStateException.class,
1151 >                         () -> sl.unlockWrite(stamp),
1152 >                         () -> sl.unlockRead(sl.tryOptimisticRead()),
1153 >                         () -> sl.unlockRead(0L));
1154 >            readUnlocker.accept(sl, stamp);
1155 >            assertUnlocked(sl);
1156 >            assertNoLongerValidStampsThrow.run();
1157 >        }
1158 >
1159 >        for (Function<StampedLock, Long> writeLocker : writeLockers())
1160 >        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
1161 >            final long stamp = writeLocker.apply(sl);
1162 >            assertValid(sl, stamp);
1163 >            assertNoLongerValidStampsThrow.run();
1164 >            assertThrows(IllegalMonitorStateException.class,
1165 >                         () -> sl.unlockRead(stamp),
1166 >                         () -> sl.unlockWrite(0L));
1167 >            writeUnlocker.accept(sl, stamp);
1168 >            assertUnlocked(sl);
1169 >            assertNoLongerValidStampsThrow.run();
1170 >        }
1171 >    }
1172 >
1173 >    /**
1174 >     * Read locks can be very deeply nested
1175 >     */
1176 >    public void testDeeplyNestedReadLocks() {
1177 >        final StampedLock lock = new StampedLock();
1178 >        final int depth = 300;
1179 >        final long[] stamps = new long[depth];
1180 >        final List<Function<StampedLock, Long>> readLockers = readLockers();
1181 >        final List<BiConsumer<StampedLock, Long>> readUnlockers = readUnlockers();
1182 >        for (int i = 0; i < depth; i++) {
1183 >            Function<StampedLock, Long> readLocker
1184 >                = readLockers.get(i % readLockers.size());
1185 >            long stamp = readLocker.apply(lock);
1186 >            assertEquals(i + 1, lock.getReadLockCount());
1187 >            assertTrue(lock.isReadLocked());
1188 >            stamps[i] = stamp;
1189 >        }
1190 >        for (int i = 0; i < depth; i++) {
1191 >            BiConsumer<StampedLock, Long> readUnlocker
1192 >                = readUnlockers.get(i % readUnlockers.size());
1193 >            assertEquals(depth - i, lock.getReadLockCount());
1194 >            assertTrue(lock.isReadLocked());
1195 >            readUnlocker.accept(lock, stamps[depth - 1 - i]);
1196 >        }
1197 >        assertUnlocked(lock);
1198 >    }
1199 >
1200 >    /**
1201 >     * Stamped locks are not reentrant.
1202 >     */
1203 >    public void testNonReentrant() throws InterruptedException {
1204 >        final StampedLock lock = new StampedLock();
1205 >        long stamp;
1206 >
1207 >        stamp = lock.writeLock();
1208 >        assertValid(lock, stamp);
1209 >        assertEquals(0L, lock.tryWriteLock(0L, DAYS));
1210 >        assertEquals(0L, lock.tryReadLock(0L, DAYS));
1211 >        assertValid(lock, stamp);
1212 >        lock.unlockWrite(stamp);
1213 >
1214 >        stamp = lock.tryWriteLock(1L, DAYS);
1215 >        assertEquals(0L, lock.tryWriteLock(0L, DAYS));
1216 >        assertValid(lock, stamp);
1217 >        lock.unlockWrite(stamp);
1218 >
1219 >        stamp = lock.readLock();
1220 >        assertEquals(0L, lock.tryWriteLock(0L, DAYS));
1221 >        assertValid(lock, stamp);
1222 >        lock.unlockRead(stamp);
1223 >    }
1224 >
1225 >    /**
1226 >     * """StampedLocks have no notion of ownership. Locks acquired in
1227 >     * one thread can be released or converted in another."""
1228 >     */
1229 >    public void testNoOwnership() throws Throwable {
1230 >        ArrayList<Future<?>> futures = new ArrayList<>();
1231 >        for (Function<StampedLock, Long> writeLocker : writeLockers())
1232 >        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
1233 >            StampedLock lock = new StampedLock();
1234 >            long stamp = writeLocker.apply(lock);
1235 >            futures.add(cachedThreadPool.submit(new CheckedRunnable() {
1236 >                public void realRun() {
1237 >                    writeUnlocker.accept(lock, stamp);
1238 >                    assertUnlocked(lock);
1239 >                    assertFalse(lock.validate(stamp));
1240 >                }}));
1241 >        }
1242 >        for (Future<?> future : futures)
1243 >            assertNull(future.get());
1244 >    }
1245 >
1246 >    /** Tries out sample usage code from StampedLock javadoc. */
1247 >    public void testSampleUsage() throws Throwable {
1248 >        class Point {
1249 >            private double x, y;
1250 >            private final StampedLock sl = new StampedLock();
1251 >
1252 >            void move(double deltaX, double deltaY) { // an exclusively locked method
1253 >                long stamp = sl.writeLock();
1254 >                try {
1255 >                    x += deltaX;
1256 >                    y += deltaY;
1257 >                } finally {
1258 >                    sl.unlockWrite(stamp);
1259 >                }
1260 >            }
1261 >
1262 >            double distanceFromOrigin() { // A read-only method
1263 >                double currentX, currentY;
1264 >                long stamp = sl.tryOptimisticRead();
1265 >                do {
1266 >                    if (stamp == 0L)
1267 >                        stamp = sl.readLock();
1268 >                    try {
1269 >                        // possibly racy reads
1270 >                        currentX = x;
1271 >                        currentY = y;
1272 >                    } finally {
1273 >                        stamp = sl.tryConvertToOptimisticRead(stamp);
1274 >                    }
1275 >                } while (stamp == 0);
1276 >                return Math.hypot(currentX, currentY);
1277 >            }
1278 >
1279 >            double distanceFromOrigin2() {
1280 >                long stamp = sl.tryOptimisticRead();
1281 >                try {
1282 >                    retryHoldingLock:
1283 >                    for (;; stamp = sl.readLock()) {
1284 >                        if (stamp == 0L)
1285 >                            continue retryHoldingLock;
1286 >                        // possibly racy reads
1287 >                        double currentX = x;
1288 >                        double currentY = y;
1289 >                        if (!sl.validate(stamp))
1290 >                            continue retryHoldingLock;
1291 >                        return Math.hypot(currentX, currentY);
1292 >                    }
1293 >                } finally {
1294 >                    if (StampedLock.isReadLockStamp(stamp))
1295 >                        sl.unlockRead(stamp);
1296 >                }
1297 >            }
1298 >
1299 >            void moveIfAtOrigin(double newX, double newY) {
1300 >                long stamp = sl.readLock();
1301 >                try {
1302 >                    while (x == 0.0 && y == 0.0) {
1303 >                        long ws = sl.tryConvertToWriteLock(stamp);
1304 >                        if (ws != 0L) {
1305 >                            stamp = ws;
1306 >                            x = newX;
1307 >                            y = newY;
1308 >                            return;
1309 >                        }
1310 >                        else {
1311 >                            sl.unlockRead(stamp);
1312 >                            stamp = sl.writeLock();
1313 >                        }
1314 >                    }
1315 >                } finally {
1316 >                    sl.unlock(stamp);
1317 >                }
1318 >            }
1319 >        }
1320 >
1321 >        Point p = new Point();
1322 >        p.move(3.0, 4.0);
1323 >        assertEquals(5.0, p.distanceFromOrigin());
1324 >        p.moveIfAtOrigin(5.0, 12.0);
1325 >        assertEquals(5.0, p.distanceFromOrigin2());
1326 >    }
1327 >
1328 >    /**
1329 >     * Stamp inspection methods work as expected, and do not inspect
1330 >     * the state of the lock itself.
1331 >     */
1332 >    public void testStampStateInspectionMethods() {
1333 >        StampedLock lock = new StampedLock();
1334 >
1335 >        assertFalse(isWriteLockStamp(0L));
1336 >        assertFalse(isReadLockStamp(0L));
1337 >        assertFalse(isLockStamp(0L));
1338 >        assertFalse(isOptimisticReadStamp(0L));
1339 >
1340 >        {
1341 >            long stamp = lock.writeLock();
1342 >            for (int i = 0; i < 2; i++) {
1343 >                assertTrue(isWriteLockStamp(stamp));
1344 >                assertFalse(isReadLockStamp(stamp));
1345 >                assertTrue(isLockStamp(stamp));
1346 >                assertFalse(isOptimisticReadStamp(stamp));
1347 >                if (i == 0)
1348 >                    lock.unlockWrite(stamp);
1349 >            }
1350 >        }
1351 >
1352 >        {
1353 >            long stamp = lock.readLock();
1354 >            for (int i = 0; i < 2; i++) {
1355 >                assertFalse(isWriteLockStamp(stamp));
1356 >                assertTrue(isReadLockStamp(stamp));
1357 >                assertTrue(isLockStamp(stamp));
1358 >                assertFalse(isOptimisticReadStamp(stamp));
1359 >                if (i == 0)
1360 >                    lock.unlockRead(stamp);
1361 >            }
1362 >        }
1363 >
1364 >        {
1365 >            long optimisticStamp = lock.tryOptimisticRead();
1366 >            long readStamp = lock.tryConvertToReadLock(optimisticStamp);
1367 >            long writeStamp = lock.tryConvertToWriteLock(readStamp);
1368 >            for (int i = 0; i < 2; i++) {
1369 >                assertFalse(isWriteLockStamp(optimisticStamp));
1370 >                assertFalse(isReadLockStamp(optimisticStamp));
1371 >                assertFalse(isLockStamp(optimisticStamp));
1372 >                assertTrue(isOptimisticReadStamp(optimisticStamp));
1373 >
1374 >                assertFalse(isWriteLockStamp(readStamp));
1375 >                assertTrue(isReadLockStamp(readStamp));
1376 >                assertTrue(isLockStamp(readStamp));
1377 >                assertFalse(isOptimisticReadStamp(readStamp));
1378 >
1379 >                assertTrue(isWriteLockStamp(writeStamp));
1380 >                assertFalse(isReadLockStamp(writeStamp));
1381 >                assertTrue(isLockStamp(writeStamp));
1382 >                assertFalse(isOptimisticReadStamp(writeStamp));
1383 >                if (i == 0)
1384 >                    lock.unlockWrite(writeStamp);
1385 >            }
1386 >        }
1387 >    }
1388  
1389   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines