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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines