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.1 by jsr166, Fri Feb 1 19:07:36 2013 UTC vs.
Revision 1.47 by dl, Tue Jan 26 13:33:06 2021 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines