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

Comparing jsr166/src/test/tck/ReentrantLockTest.java (file contents):
Revision 1.36 by jsr166, Wed Aug 25 00:07:03 2010 UTC vs.
Revision 1.62 by jsr166, Fri Jul 3 01:25:15 2015 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9 import junit.framework.*;
10 import java.util.concurrent.locks.*;
11 import java.util.concurrent.*;
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 < import java.util.*;
11 < import java.io.*;
10 >
11 > import java.util.Arrays;
12 > import java.util.Collection;
13 > import java.util.HashSet;
14 > import java.util.concurrent.CountDownLatch;
15 > import java.util.concurrent.CyclicBarrier;
16 > import java.util.concurrent.locks.Condition;
17 > import java.util.concurrent.locks.ReentrantLock;
18 >
19 > import junit.framework.AssertionFailedError;
20 > import junit.framework.Test;
21 > import junit.framework.TestSuite;
22  
23   public class ReentrantLockTest extends JSR166TestCase {
24      public static void main(String[] args) {
25 <        junit.textui.TestRunner.run(suite());
25 >        main(suite(), args);
26      }
27      public static Test suite() {
28          return new TestSuite(ReentrantLockTest.class);
29      }
30  
31      /**
32 <     * A runnable calling lockInterruptibly
32 >     * A checked runnable calling lockInterruptibly
33       */
34      class InterruptibleLockRunnable extends CheckedRunnable {
35          final ReentrantLock lock;
36 <        InterruptibleLockRunnable(ReentrantLock l) { lock = l; }
36 >        InterruptibleLockRunnable(ReentrantLock lock) { this.lock = lock; }
37          public void realRun() throws InterruptedException {
38              lock.lockInterruptibly();
39          }
40      }
41  
35
42      /**
43 <     * A runnable calling lockInterruptibly that expects to be
43 >     * A checked runnable calling lockInterruptibly that expects to be
44       * interrupted
45       */
46      class InterruptedLockRunnable extends CheckedInterruptedRunnable {
47          final ReentrantLock lock;
48 <        InterruptedLockRunnable(ReentrantLock l) { lock = l; }
48 >        InterruptedLockRunnable(ReentrantLock lock) { this.lock = lock; }
49          public void realRun() throws InterruptedException {
50              lock.lockInterruptibly();
51          }
# Line 50 | Line 56 | public class ReentrantLockTest extends J
56       */
57      static class PublicReentrantLock extends ReentrantLock {
58          PublicReentrantLock() { super(); }
59 +        PublicReentrantLock(boolean fair) { super(fair); }
60 +        public Thread getOwner() {
61 +            return super.getOwner();
62 +        }
63          public Collection<Thread> getQueuedThreads() {
64              return super.getQueuedThreads();
65          }
# Line 59 | Line 69 | public class ReentrantLockTest extends J
69      }
70  
71      /**
72 <     * Constructor sets given fairness
72 >     * Releases write lock, checking that it had a hold count of 1.
73       */
74 <    public void testConstructor() {
75 <        assertFalse(new ReentrantLock().isFair());
76 <        assertFalse(new ReentrantLock(false).isFair());
77 <        assertTrue(new ReentrantLock(true).isFair());
74 >    void releaseLock(PublicReentrantLock lock) {
75 >        assertLockedByMoi(lock);
76 >        lock.unlock();
77 >        assertFalse(lock.isHeldByCurrentThread());
78 >        assertNotLocked(lock);
79      }
80  
81      /**
82 <     * locking an unlocked lock succeeds
82 >     * Spin-waits until lock.hasQueuedThread(t) becomes true.
83 >     */
84 >    void waitForQueuedThread(PublicReentrantLock lock, Thread t) {
85 >        long startTime = System.nanoTime();
86 >        while (!lock.hasQueuedThread(t)) {
87 >            if (millisElapsedSince(startTime) > LONG_DELAY_MS)
88 >                throw new AssertionFailedError("timed out");
89 >            Thread.yield();
90 >        }
91 >        assertTrue(t.isAlive());
92 >        assertNotSame(t, lock.getOwner());
93 >    }
94 >
95 >    /**
96 >     * Checks that lock is not locked.
97 >     */
98 >    void assertNotLocked(PublicReentrantLock lock) {
99 >        assertFalse(lock.isLocked());
100 >        assertFalse(lock.isHeldByCurrentThread());
101 >        assertNull(lock.getOwner());
102 >        assertEquals(0, lock.getHoldCount());
103 >    }
104 >
105 >    /**
106 >     * Checks that lock is locked by the given thread.
107 >     */
108 >    void assertLockedBy(PublicReentrantLock lock, Thread t) {
109 >        assertTrue(lock.isLocked());
110 >        assertSame(t, lock.getOwner());
111 >        assertEquals(t == Thread.currentThread(),
112 >                     lock.isHeldByCurrentThread());
113 >        assertEquals(t == Thread.currentThread(),
114 >                     lock.getHoldCount() > 0);
115 >    }
116 >
117 >    /**
118 >     * Checks that lock is locked by the current thread.
119       */
120 <    public void testLock() {
121 <        ReentrantLock rl = new ReentrantLock();
75 <        rl.lock();
76 <        assertTrue(rl.isLocked());
77 <        rl.unlock();
78 <        assertFalse(rl.isLocked());
120 >    void assertLockedByMoi(PublicReentrantLock lock) {
121 >        assertLockedBy(lock, Thread.currentThread());
122      }
123  
124      /**
125 <     * locking an unlocked fair lock succeeds
126 <     */
127 <    public void testFairLock() {
128 <        ReentrantLock rl = new ReentrantLock(true);
129 <        rl.lock();
130 <        assertTrue(rl.isLocked());
131 <        rl.unlock();
125 >     * Checks that condition c has no waiters.
126 >     */
127 >    void assertHasNoWaiters(PublicReentrantLock lock, Condition c) {
128 >        assertHasWaiters(lock, c, new Thread[] {});
129 >    }
130 >
131 >    /**
132 >     * Checks that condition c has exactly the given waiter threads.
133 >     */
134 >    void assertHasWaiters(PublicReentrantLock lock, Condition c,
135 >                          Thread... threads) {
136 >        lock.lock();
137 >        assertEquals(threads.length > 0, lock.hasWaiters(c));
138 >        assertEquals(threads.length, lock.getWaitQueueLength(c));
139 >        assertEquals(threads.length == 0, lock.getWaitingThreads(c).isEmpty());
140 >        assertEquals(threads.length, lock.getWaitingThreads(c).size());
141 >        assertEquals(new HashSet<Thread>(lock.getWaitingThreads(c)),
142 >                     new HashSet<Thread>(Arrays.asList(threads)));
143 >        lock.unlock();
144 >    }
145 >
146 >    enum AwaitMethod { await, awaitTimed, awaitNanos, awaitUntil }
147 >
148 >    /**
149 >     * Awaits condition "indefinitely" using the specified AwaitMethod.
150 >     */
151 >    void await(Condition c, AwaitMethod awaitMethod)
152 >            throws InterruptedException {
153 >        long timeoutMillis = 2 * LONG_DELAY_MS;
154 >        switch (awaitMethod) {
155 >        case await:
156 >            c.await();
157 >            break;
158 >        case awaitTimed:
159 >            assertTrue(c.await(timeoutMillis, MILLISECONDS));
160 >            break;
161 >        case awaitNanos:
162 >            long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
163 >            long nanosRemaining = c.awaitNanos(timeoutNanos);
164 >            assertTrue(nanosRemaining > timeoutNanos / 2);
165 >            assertTrue(nanosRemaining <= timeoutNanos);
166 >            break;
167 >        case awaitUntil:
168 >            assertTrue(c.awaitUntil(delayedDate(timeoutMillis)));
169 >            break;
170 >        default:
171 >            throw new AssertionError();
172 >        }
173 >    }
174 >
175 >    /**
176 >     * Constructor sets given fairness, and is in unlocked state
177 >     */
178 >    public void testConstructor() {
179 >        PublicReentrantLock lock;
180 >
181 >        lock = new PublicReentrantLock();
182 >        assertFalse(lock.isFair());
183 >        assertNotLocked(lock);
184 >
185 >        lock = new PublicReentrantLock(true);
186 >        assertTrue(lock.isFair());
187 >        assertNotLocked(lock);
188 >
189 >        lock = new PublicReentrantLock(false);
190 >        assertFalse(lock.isFair());
191 >        assertNotLocked(lock);
192 >    }
193 >
194 >    /**
195 >     * locking an unlocked lock succeeds
196 >     */
197 >    public void testLock()      { testLock(false); }
198 >    public void testLock_fair() { testLock(true); }
199 >    public void testLock(boolean fair) {
200 >        PublicReentrantLock lock = new PublicReentrantLock(fair);
201 >        lock.lock();
202 >        assertLockedByMoi(lock);
203 >        releaseLock(lock);
204      }
205  
206      /**
207       * Unlocking an unlocked lock throws IllegalMonitorStateException
208       */
209 <    public void testUnlock_IllegalMonitorStateException() {
210 <        ReentrantLock rl = new ReentrantLock();
209 >    public void testUnlock_IMSE()      { testUnlock_IMSE(false); }
210 >    public void testUnlock_IMSE_fair() { testUnlock_IMSE(true); }
211 >    public void testUnlock_IMSE(boolean fair) {
212 >        ReentrantLock lock = new ReentrantLock(fair);
213          try {
214 <            rl.unlock();
214 >            lock.unlock();
215              shouldThrow();
216          } catch (IllegalMonitorStateException success) {}
217      }
# Line 102 | Line 219 | public class ReentrantLockTest extends J
219      /**
220       * tryLock on an unlocked lock succeeds
221       */
222 <    public void testTryLock() {
223 <        ReentrantLock rl = new ReentrantLock();
224 <        assertTrue(rl.tryLock());
225 <        assertTrue(rl.isLocked());
226 <        rl.unlock();
222 >    public void testTryLock()      { testTryLock(false); }
223 >    public void testTryLock_fair() { testTryLock(true); }
224 >    public void testTryLock(boolean fair) {
225 >        PublicReentrantLock lock = new PublicReentrantLock(fair);
226 >        assertTrue(lock.tryLock());
227 >        assertLockedByMoi(lock);
228 >        assertTrue(lock.tryLock());
229 >        assertLockedByMoi(lock);
230 >        lock.unlock();
231 >        releaseLock(lock);
232      }
233  
112
234      /**
235       * hasQueuedThreads reports whether there are waiting threads
236       */
237 <    public void testhasQueuedThreads() throws InterruptedException {
238 <        final ReentrantLock lock = new ReentrantLock();
237 >    public void testHasQueuedThreads()      { testHasQueuedThreads(false); }
238 >    public void testHasQueuedThreads_fair() { testHasQueuedThreads(true); }
239 >    public void testHasQueuedThreads(boolean fair) {
240 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
241          Thread t1 = new Thread(new InterruptedLockRunnable(lock));
242          Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
243          assertFalse(lock.hasQueuedThreads());
244          lock.lock();
245 +        assertFalse(lock.hasQueuedThreads());
246          t1.start();
247 <        Thread.sleep(SHORT_DELAY_MS);
247 >        waitForQueuedThread(lock, t1);
248          assertTrue(lock.hasQueuedThreads());
249          t2.start();
250 <        Thread.sleep(SHORT_DELAY_MS);
250 >        waitForQueuedThread(lock, t2);
251          assertTrue(lock.hasQueuedThreads());
252          t1.interrupt();
253 <        Thread.sleep(SHORT_DELAY_MS);
253 >        awaitTermination(t1);
254          assertTrue(lock.hasQueuedThreads());
255          lock.unlock();
256 <        Thread.sleep(SHORT_DELAY_MS);
256 >        awaitTermination(t2);
257          assertFalse(lock.hasQueuedThreads());
134        t1.join();
135        t2.join();
136    }
137
138    /**
139     * getQueueLength reports number of waiting threads
140     */
141    public void testGetQueueLength() throws InterruptedException {
142        final ReentrantLock lock = new ReentrantLock();
143        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
144        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
145        assertEquals(0, lock.getQueueLength());
146        lock.lock();
147        t1.start();
148        Thread.sleep(SHORT_DELAY_MS);
149        assertEquals(1, lock.getQueueLength());
150        t2.start();
151        Thread.sleep(SHORT_DELAY_MS);
152        assertEquals(2, lock.getQueueLength());
153        t1.interrupt();
154        Thread.sleep(SHORT_DELAY_MS);
155        assertEquals(1, lock.getQueueLength());
156        lock.unlock();
157        Thread.sleep(SHORT_DELAY_MS);
158        assertEquals(0, lock.getQueueLength());
159        t1.join();
160        t2.join();
258      }
259  
260      /**
261       * getQueueLength reports number of waiting threads
262       */
263 <    public void testGetQueueLength_fair() throws InterruptedException {
264 <        final ReentrantLock lock = new ReentrantLock(true);
263 >    public void testGetQueueLength()      { testGetQueueLength(false); }
264 >    public void testGetQueueLength_fair() { testGetQueueLength(true); }
265 >    public void testGetQueueLength(boolean fair) {
266 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
267          Thread t1 = new Thread(new InterruptedLockRunnable(lock));
268          Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
269          assertEquals(0, lock.getQueueLength());
270          lock.lock();
271          t1.start();
272 <        Thread.sleep(SHORT_DELAY_MS);
272 >        waitForQueuedThread(lock, t1);
273          assertEquals(1, lock.getQueueLength());
274          t2.start();
275 <        Thread.sleep(SHORT_DELAY_MS);
275 >        waitForQueuedThread(lock, t2);
276          assertEquals(2, lock.getQueueLength());
277          t1.interrupt();
278 <        Thread.sleep(SHORT_DELAY_MS);
278 >        awaitTermination(t1);
279          assertEquals(1, lock.getQueueLength());
280          lock.unlock();
281 <        Thread.sleep(SHORT_DELAY_MS);
281 >        awaitTermination(t2);
282          assertEquals(0, lock.getQueueLength());
184        t1.join();
185        t2.join();
283      }
284  
285      /**
286       * hasQueuedThread(null) throws NPE
287       */
288 <    public void testHasQueuedThreadNPE() {
289 <        final ReentrantLock sync = new ReentrantLock();
288 >    public void testHasQueuedThreadNPE()      { testHasQueuedThreadNPE(false); }
289 >    public void testHasQueuedThreadNPE_fair() { testHasQueuedThreadNPE(true); }
290 >    public void testHasQueuedThreadNPE(boolean fair) {
291 >        final ReentrantLock lock = new ReentrantLock(fair);
292          try {
293 <            sync.hasQueuedThread(null);
293 >            lock.hasQueuedThread(null);
294              shouldThrow();
295          } catch (NullPointerException success) {}
296      }
297  
298      /**
299 <     * hasQueuedThread reports whether a thread is queued.
299 >     * hasQueuedThread reports whether a thread is queued
300       */
301 <    public void testHasQueuedThread() throws InterruptedException {
302 <        final ReentrantLock sync = new ReentrantLock();
303 <        Thread t1 = new Thread(new InterruptedLockRunnable(sync));
304 <        Thread t2 = new Thread(new InterruptibleLockRunnable(sync));
305 <        assertFalse(sync.hasQueuedThread(t1));
306 <        assertFalse(sync.hasQueuedThread(t2));
307 <        sync.lock();
301 >    public void testHasQueuedThread()      { testHasQueuedThread(false); }
302 >    public void testHasQueuedThread_fair() { testHasQueuedThread(true); }
303 >    public void testHasQueuedThread(boolean fair) {
304 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
305 >        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
306 >        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
307 >        assertFalse(lock.hasQueuedThread(t1));
308 >        assertFalse(lock.hasQueuedThread(t2));
309 >        lock.lock();
310          t1.start();
311 <        Thread.sleep(SHORT_DELAY_MS);
312 <        assertTrue(sync.hasQueuedThread(t1));
311 >        waitForQueuedThread(lock, t1);
312 >        assertTrue(lock.hasQueuedThread(t1));
313 >        assertFalse(lock.hasQueuedThread(t2));
314          t2.start();
315 <        Thread.sleep(SHORT_DELAY_MS);
316 <        assertTrue(sync.hasQueuedThread(t1));
317 <        assertTrue(sync.hasQueuedThread(t2));
315 >        waitForQueuedThread(lock, t2);
316 >        assertTrue(lock.hasQueuedThread(t1));
317 >        assertTrue(lock.hasQueuedThread(t2));
318          t1.interrupt();
319 <        Thread.sleep(SHORT_DELAY_MS);
320 <        assertFalse(sync.hasQueuedThread(t1));
321 <        assertTrue(sync.hasQueuedThread(t2));
322 <        sync.unlock();
323 <        Thread.sleep(SHORT_DELAY_MS);
324 <        assertFalse(sync.hasQueuedThread(t1));
325 <        Thread.sleep(SHORT_DELAY_MS);
224 <        assertFalse(sync.hasQueuedThread(t2));
225 <        t1.join();
226 <        t2.join();
319 >        awaitTermination(t1);
320 >        assertFalse(lock.hasQueuedThread(t1));
321 >        assertTrue(lock.hasQueuedThread(t2));
322 >        lock.unlock();
323 >        awaitTermination(t2);
324 >        assertFalse(lock.hasQueuedThread(t1));
325 >        assertFalse(lock.hasQueuedThread(t2));
326      }
327  
229
328      /**
329       * getQueuedThreads includes waiting threads
330       */
331 <    public void testGetQueuedThreads() throws InterruptedException {
332 <        final PublicReentrantLock lock = new PublicReentrantLock();
331 >    public void testGetQueuedThreads()      { testGetQueuedThreads(false); }
332 >    public void testGetQueuedThreads_fair() { testGetQueuedThreads(true); }
333 >    public void testGetQueuedThreads(boolean fair) {
334 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
335          Thread t1 = new Thread(new InterruptedLockRunnable(lock));
336          Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
337          assertTrue(lock.getQueuedThreads().isEmpty());
338          lock.lock();
339          assertTrue(lock.getQueuedThreads().isEmpty());
340          t1.start();
341 <        Thread.sleep(SHORT_DELAY_MS);
341 >        waitForQueuedThread(lock, t1);
342 >        assertEquals(1, lock.getQueuedThreads().size());
343          assertTrue(lock.getQueuedThreads().contains(t1));
344          t2.start();
345 <        Thread.sleep(SHORT_DELAY_MS);
345 >        waitForQueuedThread(lock, t2);
346 >        assertEquals(2, lock.getQueuedThreads().size());
347          assertTrue(lock.getQueuedThreads().contains(t1));
348          assertTrue(lock.getQueuedThreads().contains(t2));
349          t1.interrupt();
350 <        Thread.sleep(SHORT_DELAY_MS);
350 >        awaitTermination(t1);
351          assertFalse(lock.getQueuedThreads().contains(t1));
352          assertTrue(lock.getQueuedThreads().contains(t2));
353 +        assertEquals(1, lock.getQueuedThreads().size());
354          lock.unlock();
355 <        Thread.sleep(SHORT_DELAY_MS);
355 >        awaitTermination(t2);
356          assertTrue(lock.getQueuedThreads().isEmpty());
254        t1.join();
255        t2.join();
357      }
358  
258
359      /**
360 <     * timed tryLock is interruptible.
360 >     * timed tryLock is interruptible
361       */
362 <    public void testInterruptedException2() throws InterruptedException {
363 <        final ReentrantLock lock = new ReentrantLock();
362 >    public void testTryLock_Interruptible()      { testTryLock_Interruptible(false); }
363 >    public void testTryLock_Interruptible_fair() { testTryLock_Interruptible(true); }
364 >    public void testTryLock_Interruptible(boolean fair) {
365 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
366          lock.lock();
367 <        Thread t = new Thread(new CheckedInterruptedRunnable() {
367 >        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
368              public void realRun() throws InterruptedException {
369 <                lock.tryLock(MEDIUM_DELAY_MS,MILLISECONDS);
369 >                lock.tryLock(2 * LONG_DELAY_MS, MILLISECONDS);
370              }});
371  
372 <        t.start();
271 <        Thread.sleep(SHORT_DELAY_MS);
372 >        waitForQueuedThread(lock, t);
373          t.interrupt();
374 <        t.join();
374 >        awaitTermination(t);
375 >        releaseLock(lock);
376      }
377  
276
378      /**
379 <     * TryLock on a locked lock fails
379 >     * tryLock on a locked lock fails
380       */
381 <    public void testTryLockWhenLocked() throws InterruptedException {
382 <        final ReentrantLock lock = new ReentrantLock();
381 >    public void testTryLockWhenLocked()      { testTryLockWhenLocked(false); }
382 >    public void testTryLockWhenLocked_fair() { testTryLockWhenLocked(true); }
383 >    public void testTryLockWhenLocked(boolean fair) {
384 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
385          lock.lock();
386 <        Thread t = new Thread(new CheckedRunnable() {
386 >        Thread t = newStartedThread(new CheckedRunnable() {
387              public void realRun() {
388 <                threadAssertFalse(lock.tryLock());
388 >                assertFalse(lock.tryLock());
389              }});
390  
391 <        t.start();
392 <        t.join();
290 <        lock.unlock();
391 >        awaitTermination(t);
392 >        releaseLock(lock);
393      }
394  
395      /**
396       * Timed tryLock on a locked lock times out
397       */
398 <    public void testTryLock_Timeout() throws InterruptedException {
399 <        final ReentrantLock lock = new ReentrantLock();
398 >    public void testTryLock_Timeout()      { testTryLock_Timeout(false); }
399 >    public void testTryLock_Timeout_fair() { testTryLock_Timeout(true); }
400 >    public void testTryLock_Timeout(boolean fair) {
401 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
402          lock.lock();
403 <        Thread t = new Thread(new CheckedRunnable() {
403 >        Thread t = newStartedThread(new CheckedRunnable() {
404              public void realRun() throws InterruptedException {
405 <                threadAssertFalse(lock.tryLock(1, MILLISECONDS));
405 >                long startTime = System.nanoTime();
406 >                long timeoutMillis = 10;
407 >                assertFalse(lock.tryLock(timeoutMillis, MILLISECONDS));
408 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
409              }});
410  
411 <        t.start();
412 <        t.join();
306 <        lock.unlock();
411 >        awaitTermination(t);
412 >        releaseLock(lock);
413      }
414  
415      /**
416       * getHoldCount returns number of recursive holds
417       */
418 <    public void testGetHoldCount() {
419 <        ReentrantLock lock = new ReentrantLock();
418 >    public void testGetHoldCount()      { testGetHoldCount(false); }
419 >    public void testGetHoldCount_fair() { testGetHoldCount(true); }
420 >    public void testGetHoldCount(boolean fair) {
421 >        ReentrantLock lock = new ReentrantLock(fair);
422          for (int i = 1; i <= SIZE; i++) {
423              lock.lock();
424              assertEquals(i, lock.getHoldCount());
425          }
426          for (int i = SIZE; i > 0; i--) {
427              lock.unlock();
428 <            assertEquals(i-1, lock.getHoldCount());
428 >            assertEquals(i - 1, lock.getHoldCount());
429          }
430      }
431  
324
432      /**
433       * isLocked is true when locked and false when not
434       */
435 <    public void testIsLocked() throws InterruptedException {
436 <        final ReentrantLock lock = new ReentrantLock();
437 <        lock.lock();
438 <        assertTrue(lock.isLocked());
439 <        lock.unlock();
440 <        assertFalse(lock.isLocked());
441 <        Thread t = new Thread(new CheckedRunnable() {
442 <            public void realRun() throws InterruptedException {
443 <                lock.lock();
444 <                Thread.sleep(SMALL_DELAY_MS);
445 <                lock.unlock();
446 <            }});
447 <
448 <        t.start();
449 <        Thread.sleep(SHORT_DELAY_MS);
450 <        assertTrue(lock.isLocked());
451 <        t.join();
452 <        assertFalse(lock.isLocked());
453 <    }
454 <
455 <
456 <    /**
457 <     * lockInterruptibly is interruptible.
458 <     */
459 <    public void testLockInterruptibly1() throws InterruptedException {
460 <        final ReentrantLock lock = new ReentrantLock();
461 <        lock.lock();
462 <        Thread t = new Thread(new InterruptedLockRunnable(lock));
463 <        t.start();
464 <        Thread.sleep(SHORT_DELAY_MS);
358 <        t.interrupt();
359 <        Thread.sleep(SHORT_DELAY_MS);
360 <        lock.unlock();
361 <        t.join();
435 >    public void testIsLocked()      { testIsLocked(false); }
436 >    public void testIsLocked_fair() { testIsLocked(true); }
437 >    public void testIsLocked(boolean fair) {
438 >        try {
439 >            final ReentrantLock lock = new ReentrantLock(fair);
440 >            assertFalse(lock.isLocked());
441 >            lock.lock();
442 >            assertTrue(lock.isLocked());
443 >            lock.lock();
444 >            assertTrue(lock.isLocked());
445 >            lock.unlock();
446 >            assertTrue(lock.isLocked());
447 >            lock.unlock();
448 >            assertFalse(lock.isLocked());
449 >            final CyclicBarrier barrier = new CyclicBarrier(2);
450 >            Thread t = newStartedThread(new CheckedRunnable() {
451 >                    public void realRun() throws Exception {
452 >                        lock.lock();
453 >                        assertTrue(lock.isLocked());
454 >                        barrier.await();
455 >                        barrier.await();
456 >                        lock.unlock();
457 >                    }});
458 >
459 >            barrier.await();
460 >            assertTrue(lock.isLocked());
461 >            barrier.await();
462 >            awaitTermination(t);
463 >            assertFalse(lock.isLocked());
464 >        } catch (Exception fail) { threadUnexpectedException(fail); }
465      }
466  
467      /**
468       * lockInterruptibly succeeds when unlocked, else is interruptible
469       */
470 <    public void testLockInterruptibly2() throws InterruptedException {
471 <        final ReentrantLock lock = new ReentrantLock();
472 <        lock.lockInterruptibly();
473 <        Thread t = new Thread(new InterruptedLockRunnable(lock));
474 <        t.start();
475 <        Thread.sleep(SHORT_DELAY_MS);
470 >    public void testLockInterruptibly()      { testLockInterruptibly(false); }
471 >    public void testLockInterruptibly_fair() { testLockInterruptibly(true); }
472 >    public void testLockInterruptibly(boolean fair) {
473 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
474 >        try {
475 >            lock.lockInterruptibly();
476 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
477 >        assertLockedByMoi(lock);
478 >        Thread t = newStartedThread(new InterruptedLockRunnable(lock));
479 >        waitForQueuedThread(lock, t);
480          t.interrupt();
481          assertTrue(lock.isLocked());
482          assertTrue(lock.isHeldByCurrentThread());
483 <        t.join();
483 >        awaitTermination(t);
484 >        releaseLock(lock);
485      }
486  
487      /**
488       * Calling await without holding lock throws IllegalMonitorStateException
489       */
490 <    public void testAwait_IllegalMonitor() throws InterruptedException {
491 <        final ReentrantLock lock = new ReentrantLock();
492 <        final Condition c = lock.newCondition();
493 <        try {
494 <            c.await();
495 <            shouldThrow();
496 <        } catch (IllegalMonitorStateException success) {}
490 >    public void testAwait_IMSE()      { testAwait_IMSE(false); }
491 >    public void testAwait_IMSE_fair() { testAwait_IMSE(true); }
492 >    public void testAwait_IMSE(boolean fair) {
493 >        final ReentrantLock lock = new ReentrantLock(fair);
494 >        final Condition c = lock.newCondition();
495 >        for (AwaitMethod awaitMethod : AwaitMethod.values()) {
496 >            long startTime = System.nanoTime();
497 >            try {
498 >                await(c, awaitMethod);
499 >                shouldThrow();
500 >            } catch (IllegalMonitorStateException success) {
501 >            } catch (InterruptedException e) { threadUnexpectedException(e); }
502 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
503 >        }
504      }
505  
506      /**
507       * Calling signal without holding lock throws IllegalMonitorStateException
508       */
509 <    public void testSignal_IllegalMonitor() {
510 <        final ReentrantLock lock = new ReentrantLock();
509 >    public void testSignal_IMSE()      { testSignal_IMSE(false); }
510 >    public void testSignal_IMSE_fair() { testSignal_IMSE(true); }
511 >    public void testSignal_IMSE(boolean fair) {
512 >        final ReentrantLock lock = new ReentrantLock(fair);
513          final Condition c = lock.newCondition();
514          try {
515              c.signal();
# Line 403 | Line 520 | public class ReentrantLockTest extends J
520      /**
521       * awaitNanos without a signal times out
522       */
523 <    public void testAwaitNanos_Timeout() throws InterruptedException {
524 <        final ReentrantLock lock = new ReentrantLock();
525 <        final Condition c = lock.newCondition();
526 <        lock.lock();
527 <        long t = c.awaitNanos(100);
528 <        assertTrue(t <= 0);
529 <        lock.unlock();
523 >    public void testAwaitNanos_Timeout()      { testAwaitNanos_Timeout(false); }
524 >    public void testAwaitNanos_Timeout_fair() { testAwaitNanos_Timeout(true); }
525 >    public void testAwaitNanos_Timeout(boolean fair) {
526 >        try {
527 >            final ReentrantLock lock = new ReentrantLock(fair);
528 >            final Condition c = lock.newCondition();
529 >            lock.lock();
530 >            long startTime = System.nanoTime();
531 >            long timeoutMillis = 10;
532 >            long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
533 >            long nanosRemaining = c.awaitNanos(timeoutNanos);
534 >            assertTrue(nanosRemaining <= 0);
535 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
536 >            lock.unlock();
537 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
538      }
539  
540      /**
541 <     *  timed await without a signal times out
541 >     * timed await without a signal times out
542       */
543 <    public void testAwait_Timeout() throws InterruptedException {
544 <        final ReentrantLock lock = new ReentrantLock();
545 <        final Condition c = lock.newCondition();
546 <        lock.lock();
547 <        assertFalse(c.await(SHORT_DELAY_MS, MILLISECONDS));
548 <        lock.unlock();
543 >    public void testAwait_Timeout()      { testAwait_Timeout(false); }
544 >    public void testAwait_Timeout_fair() { testAwait_Timeout(true); }
545 >    public void testAwait_Timeout(boolean fair) {
546 >        try {
547 >            final ReentrantLock lock = new ReentrantLock(fair);
548 >            final Condition c = lock.newCondition();
549 >            lock.lock();
550 >            long startTime = System.nanoTime();
551 >            long timeoutMillis = 10;
552 >            assertFalse(c.await(timeoutMillis, MILLISECONDS));
553 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
554 >            lock.unlock();
555 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
556      }
557  
558      /**
559       * awaitUntil without a signal times out
560       */
561 <    public void testAwaitUntil_Timeout() throws InterruptedException {
562 <        final ReentrantLock lock = new ReentrantLock();
563 <        final Condition c = lock.newCondition();
564 <        lock.lock();
565 <        java.util.Date d = new java.util.Date();
566 <        assertFalse(c.awaitUntil(new java.util.Date(d.getTime() + 10)));
567 <        lock.unlock();
561 >    public void testAwaitUntil_Timeout()      { testAwaitUntil_Timeout(false); }
562 >    public void testAwaitUntil_Timeout_fair() { testAwaitUntil_Timeout(true); }
563 >    public void testAwaitUntil_Timeout(boolean fair) {
564 >        try {
565 >            final ReentrantLock lock = new ReentrantLock(fair);
566 >            final Condition c = lock.newCondition();
567 >            lock.lock();
568 >            long startTime = System.nanoTime();
569 >            assertFalse(c.awaitUntil(delayedDate(timeoutMillis())));
570 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
571 >            lock.unlock();
572 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
573      }
574  
575      /**
576       * await returns when signalled
577       */
578 <    public void testAwait() throws InterruptedException {
579 <        final ReentrantLock lock = new ReentrantLock();
578 >    public void testAwait()      { testAwait(false); }
579 >    public void testAwait_fair() { testAwait(true); }
580 >    public void testAwait(boolean fair) {
581 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
582          final Condition c = lock.newCondition();
583 <        Thread t = new Thread(new CheckedRunnable() {
583 >        final CountDownLatch locked = new CountDownLatch(1);
584 >        Thread t = newStartedThread(new CheckedRunnable() {
585              public void realRun() throws InterruptedException {
586                  lock.lock();
587 +                locked.countDown();
588                  c.await();
589                  lock.unlock();
590              }});
591  
592 <        t.start();
452 <        Thread.sleep(SHORT_DELAY_MS);
592 >        await(locked);
593          lock.lock();
594 +        assertHasWaiters(lock, c, t);
595          c.signal();
596 +        assertHasNoWaiters(lock, c);
597 +        assertTrue(t.isAlive());
598          lock.unlock();
599 <        t.join(SHORT_DELAY_MS);
457 <        assertFalse(t.isAlive());
599 >        awaitTermination(t);
600      }
601  
602      /**
603       * hasWaiters throws NPE if null
604       */
605 <    public void testHasWaitersNPE() {
606 <        final ReentrantLock lock = new ReentrantLock();
605 >    public void testHasWaitersNPE()      { testHasWaitersNPE(false); }
606 >    public void testHasWaitersNPE_fair() { testHasWaitersNPE(true); }
607 >    public void testHasWaitersNPE(boolean fair) {
608 >        final ReentrantLock lock = new ReentrantLock(fair);
609          try {
610              lock.hasWaiters(null);
611              shouldThrow();
# Line 471 | Line 615 | public class ReentrantLockTest extends J
615      /**
616       * getWaitQueueLength throws NPE if null
617       */
618 <    public void testGetWaitQueueLengthNPE() {
619 <        final ReentrantLock lock = new ReentrantLock();
618 >    public void testGetWaitQueueLengthNPE()      { testGetWaitQueueLengthNPE(false); }
619 >    public void testGetWaitQueueLengthNPE_fair() { testGetWaitQueueLengthNPE(true); }
620 >    public void testGetWaitQueueLengthNPE(boolean fair) {
621 >        final ReentrantLock lock = new ReentrantLock(fair);
622          try {
623              lock.getWaitQueueLength(null);
624              shouldThrow();
625          } catch (NullPointerException success) {}
626      }
627  
482
628      /**
629       * getWaitingThreads throws NPE if null
630       */
631 <    public void testGetWaitingThreadsNPE() {
632 <        final PublicReentrantLock lock = new PublicReentrantLock();
631 >    public void testGetWaitingThreadsNPE()      { testGetWaitingThreadsNPE(false); }
632 >    public void testGetWaitingThreadsNPE_fair() { testGetWaitingThreadsNPE(true); }
633 >    public void testGetWaitingThreadsNPE(boolean fair) {
634 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
635          try {
636              lock.getWaitingThreads(null);
637              shouldThrow();
638          } catch (NullPointerException success) {}
639      }
640  
494
641      /**
642 <     * hasWaiters throws IAE if not owned
642 >     * hasWaiters throws IllegalArgumentException if not owned
643       */
644 <    public void testHasWaitersIAE() {
645 <        final ReentrantLock lock = new ReentrantLock();
644 >    public void testHasWaitersIAE()      { testHasWaitersIAE(false); }
645 >    public void testHasWaitersIAE_fair() { testHasWaitersIAE(true); }
646 >    public void testHasWaitersIAE(boolean fair) {
647 >        final ReentrantLock lock = new ReentrantLock(fair);
648          final Condition c = lock.newCondition();
649 <        final ReentrantLock lock2 = new ReentrantLock();
649 >        final ReentrantLock lock2 = new ReentrantLock(fair);
650          try {
651              lock2.hasWaiters(c);
652              shouldThrow();
# Line 506 | Line 654 | public class ReentrantLockTest extends J
654      }
655  
656      /**
657 <     * hasWaiters throws IMSE if not locked
657 >     * hasWaiters throws IllegalMonitorStateException if not locked
658       */
659 <    public void testHasWaitersIMSE() {
660 <        final ReentrantLock lock = new ReentrantLock();
659 >    public void testHasWaitersIMSE()      { testHasWaitersIMSE(false); }
660 >    public void testHasWaitersIMSE_fair() { testHasWaitersIMSE(true); }
661 >    public void testHasWaitersIMSE(boolean fair) {
662 >        final ReentrantLock lock = new ReentrantLock(fair);
663          final Condition c = lock.newCondition();
664          try {
665              lock.hasWaiters(c);
# Line 517 | Line 667 | public class ReentrantLockTest extends J
667          } catch (IllegalMonitorStateException success) {}
668      }
669  
520
670      /**
671 <     * getWaitQueueLength throws IAE if not owned
671 >     * getWaitQueueLength throws IllegalArgumentException if not owned
672       */
673 <    public void testGetWaitQueueLengthIAE() {
674 <        final ReentrantLock lock = new ReentrantLock();
673 >    public void testGetWaitQueueLengthIAE()      { testGetWaitQueueLengthIAE(false); }
674 >    public void testGetWaitQueueLengthIAE_fair() { testGetWaitQueueLengthIAE(true); }
675 >    public void testGetWaitQueueLengthIAE(boolean fair) {
676 >        final ReentrantLock lock = new ReentrantLock(fair);
677          final Condition c = lock.newCondition();
678 <        final ReentrantLock lock2 = new ReentrantLock();
678 >        final ReentrantLock lock2 = new ReentrantLock(fair);
679          try {
680              lock2.getWaitQueueLength(c);
681              shouldThrow();
# Line 532 | Line 683 | public class ReentrantLockTest extends J
683      }
684  
685      /**
686 <     * getWaitQueueLength throws IMSE if not locked
686 >     * getWaitQueueLength throws IllegalMonitorStateException if not locked
687       */
688 <    public void testGetWaitQueueLengthIMSE() {
689 <        final ReentrantLock lock = new ReentrantLock();
688 >    public void testGetWaitQueueLengthIMSE()      { testGetWaitQueueLengthIMSE(false); }
689 >    public void testGetWaitQueueLengthIMSE_fair() { testGetWaitQueueLengthIMSE(true); }
690 >    public void testGetWaitQueueLengthIMSE(boolean fair) {
691 >        final ReentrantLock lock = new ReentrantLock(fair);
692          final Condition c = lock.newCondition();
693          try {
694              lock.getWaitQueueLength(c);
# Line 543 | Line 696 | public class ReentrantLockTest extends J
696          } catch (IllegalMonitorStateException success) {}
697      }
698  
546
699      /**
700 <     * getWaitingThreads throws IAE if not owned
700 >     * getWaitingThreads throws IllegalArgumentException if not owned
701       */
702 <    public void testGetWaitingThreadsIAE() {
703 <        final PublicReentrantLock lock = new PublicReentrantLock();
702 >    public void testGetWaitingThreadsIAE()      { testGetWaitingThreadsIAE(false); }
703 >    public void testGetWaitingThreadsIAE_fair() { testGetWaitingThreadsIAE(true); }
704 >    public void testGetWaitingThreadsIAE(boolean fair) {
705 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
706          final Condition c = lock.newCondition();
707 <        final PublicReentrantLock lock2 = new PublicReentrantLock();
707 >        final PublicReentrantLock lock2 = new PublicReentrantLock(fair);
708          try {
709              lock2.getWaitingThreads(c);
710              shouldThrow();
# Line 558 | Line 712 | public class ReentrantLockTest extends J
712      }
713  
714      /**
715 <     * getWaitingThreads throws IMSE if not locked
715 >     * getWaitingThreads throws IllegalMonitorStateException if not locked
716       */
717 <    public void testGetWaitingThreadsIMSE() {
718 <        final PublicReentrantLock lock = new PublicReentrantLock();
717 >    public void testGetWaitingThreadsIMSE()      { testGetWaitingThreadsIMSE(false); }
718 >    public void testGetWaitingThreadsIMSE_fair() { testGetWaitingThreadsIMSE(true); }
719 >    public void testGetWaitingThreadsIMSE(boolean fair) {
720 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
721          final Condition c = lock.newCondition();
722          try {
723              lock.getWaitingThreads(c);
# Line 569 | Line 725 | public class ReentrantLockTest extends J
725          } catch (IllegalMonitorStateException success) {}
726      }
727  
572
728      /**
729       * hasWaiters returns true when a thread is waiting, else false
730       */
731 <    public void testHasWaiters() throws InterruptedException {
732 <        final ReentrantLock lock = new ReentrantLock();
731 >    public void testHasWaiters()      { testHasWaiters(false); }
732 >    public void testHasWaiters_fair() { testHasWaiters(true); }
733 >    public void testHasWaiters(boolean fair) {
734 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
735          final Condition c = lock.newCondition();
736 <        Thread t = new Thread(new CheckedRunnable() {
736 >        final CountDownLatch pleaseSignal = new CountDownLatch(1);
737 >        Thread t = newStartedThread(new CheckedRunnable() {
738              public void realRun() throws InterruptedException {
739                  lock.lock();
740 <                threadAssertFalse(lock.hasWaiters(c));
741 <                threadAssertEquals(0, lock.getWaitQueueLength(c));
740 >                assertHasNoWaiters(lock, c);
741 >                assertFalse(lock.hasWaiters(c));
742 >                pleaseSignal.countDown();
743                  c.await();
744 +                assertHasNoWaiters(lock, c);
745 +                assertFalse(lock.hasWaiters(c));
746                  lock.unlock();
747              }});
748  
749 <        t.start();
589 <        Thread.sleep(SHORT_DELAY_MS);
749 >        await(pleaseSignal);
750          lock.lock();
751 +        assertHasWaiters(lock, c, t);
752          assertTrue(lock.hasWaiters(c));
592        assertEquals(1, lock.getWaitQueueLength(c));
753          c.signal();
754 <        lock.unlock();
595 <        Thread.sleep(SHORT_DELAY_MS);
596 <        lock.lock();
754 >        assertHasNoWaiters(lock, c);
755          assertFalse(lock.hasWaiters(c));
598        assertEquals(0, lock.getWaitQueueLength(c));
756          lock.unlock();
757 <        t.join(SHORT_DELAY_MS);
758 <        assertFalse(t.isAlive());
757 >        awaitTermination(t);
758 >        assertHasNoWaiters(lock, c);
759      }
760  
761      /**
762       * getWaitQueueLength returns number of waiting threads
763       */
764 <    public void testGetWaitQueueLength() throws InterruptedException {
765 <        final ReentrantLock lock = new ReentrantLock();
764 >    public void testGetWaitQueueLength()      { testGetWaitQueueLength(false); }
765 >    public void testGetWaitQueueLength_fair() { testGetWaitQueueLength(true); }
766 >    public void testGetWaitQueueLength(boolean fair) {
767 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
768          final Condition c = lock.newCondition();
769 +        final CountDownLatch locked1 = new CountDownLatch(1);
770 +        final CountDownLatch locked2 = new CountDownLatch(1);
771          Thread t1 = new Thread(new CheckedRunnable() {
772              public void realRun() throws InterruptedException {
773                  lock.lock();
774 <                threadAssertFalse(lock.hasWaiters(c));
775 <                threadAssertEquals(0, lock.getWaitQueueLength(c));
774 >                assertFalse(lock.hasWaiters(c));
775 >                assertEquals(0, lock.getWaitQueueLength(c));
776 >                locked1.countDown();
777                  c.await();
778                  lock.unlock();
779              }});
# Line 619 | Line 781 | public class ReentrantLockTest extends J
781          Thread t2 = new Thread(new CheckedRunnable() {
782              public void realRun() throws InterruptedException {
783                  lock.lock();
784 <                threadAssertTrue(lock.hasWaiters(c));
785 <                threadAssertEquals(1, lock.getWaitQueueLength(c));
784 >                assertTrue(lock.hasWaiters(c));
785 >                assertEquals(1, lock.getWaitQueueLength(c));
786 >                locked2.countDown();
787                  c.await();
788                  lock.unlock();
789              }});
790  
791 +        lock.lock();
792 +        assertEquals(0, lock.getWaitQueueLength(c));
793 +        lock.unlock();
794 +
795          t1.start();
796 <        Thread.sleep(SHORT_DELAY_MS);
796 >        await(locked1);
797 >
798 >        lock.lock();
799 >        assertHasWaiters(lock, c, t1);
800 >        assertEquals(1, lock.getWaitQueueLength(c));
801 >        lock.unlock();
802 >
803          t2.start();
804 <        Thread.sleep(SHORT_DELAY_MS);
804 >        await(locked2);
805 >
806          lock.lock();
807 <        assertTrue(lock.hasWaiters(c));
807 >        assertHasWaiters(lock, c, t1, t2);
808          assertEquals(2, lock.getWaitQueueLength(c));
809          c.signalAll();
810 +        assertHasNoWaiters(lock, c);
811          lock.unlock();
812 <        Thread.sleep(SHORT_DELAY_MS);
813 <        lock.lock();
814 <        assertFalse(lock.hasWaiters(c));
815 <        assertEquals(0, lock.getWaitQueueLength(c));
816 <        lock.unlock();
642 <        t1.join(SHORT_DELAY_MS);
643 <        t2.join(SHORT_DELAY_MS);
644 <        assertFalse(t1.isAlive());
645 <        assertFalse(t2.isAlive());
812 >
813 >        awaitTermination(t1);
814 >        awaitTermination(t2);
815 >
816 >        assertHasNoWaiters(lock, c);
817      }
818  
819      /**
820       * getWaitingThreads returns only and all waiting threads
821       */
822 <    public void testGetWaitingThreads() throws InterruptedException {
823 <        final PublicReentrantLock lock = new PublicReentrantLock();
822 >    public void testGetWaitingThreads()      { testGetWaitingThreads(false); }
823 >    public void testGetWaitingThreads_fair() { testGetWaitingThreads(true); }
824 >    public void testGetWaitingThreads(boolean fair) {
825 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
826          final Condition c = lock.newCondition();
827 +        final CountDownLatch locked1 = new CountDownLatch(1);
828 +        final CountDownLatch locked2 = new CountDownLatch(1);
829          Thread t1 = new Thread(new CheckedRunnable() {
830              public void realRun() throws InterruptedException {
831                  lock.lock();
832 <                threadAssertTrue(lock.getWaitingThreads(c).isEmpty());
832 >                assertTrue(lock.getWaitingThreads(c).isEmpty());
833 >                locked1.countDown();
834                  c.await();
835                  lock.unlock();
836              }});
# Line 662 | Line 838 | public class ReentrantLockTest extends J
838          Thread t2 = new Thread(new CheckedRunnable() {
839              public void realRun() throws InterruptedException {
840                  lock.lock();
841 <                threadAssertFalse(lock.getWaitingThreads(c).isEmpty());
841 >                assertFalse(lock.getWaitingThreads(c).isEmpty());
842 >                locked2.countDown();
843                  c.await();
844                  lock.unlock();
845              }});
# Line 670 | Line 847 | public class ReentrantLockTest extends J
847          lock.lock();
848          assertTrue(lock.getWaitingThreads(c).isEmpty());
849          lock.unlock();
850 +
851          t1.start();
852 <        Thread.sleep(SHORT_DELAY_MS);
852 >        await(locked1);
853 >
854 >        lock.lock();
855 >        assertHasWaiters(lock, c, t1);
856 >        assertTrue(lock.getWaitingThreads(c).contains(t1));
857 >        assertFalse(lock.getWaitingThreads(c).contains(t2));
858 >        assertEquals(1, lock.getWaitingThreads(c).size());
859 >        lock.unlock();
860 >
861          t2.start();
862 <        Thread.sleep(SHORT_DELAY_MS);
862 >        await(locked2);
863 >
864          lock.lock();
865 <        assertTrue(lock.hasWaiters(c));
865 >        assertHasWaiters(lock, c, t1, t2);
866          assertTrue(lock.getWaitingThreads(c).contains(t1));
867          assertTrue(lock.getWaitingThreads(c).contains(t2));
868 +        assertEquals(2, lock.getWaitingThreads(c).size());
869          c.signalAll();
870 +        assertHasNoWaiters(lock, c);
871          lock.unlock();
683        Thread.sleep(SHORT_DELAY_MS);
684        lock.lock();
685        assertFalse(lock.hasWaiters(c));
686        assertTrue(lock.getWaitingThreads(c).isEmpty());
687        lock.unlock();
688        t1.join(SHORT_DELAY_MS);
689        t2.join(SHORT_DELAY_MS);
690        assertFalse(t1.isAlive());
691        assertFalse(t2.isAlive());
692    }
693
694    /** A helper class for uninterruptible wait tests */
695    class UninterruptibleThread extends Thread {
696        private ReentrantLock lock;
697        private Condition c;
698
699        public volatile boolean canAwake = false;
700        public volatile boolean interrupted = false;
701        public volatile boolean lockStarted = false;
702
703        public UninterruptibleThread(ReentrantLock lock, Condition c) {
704            this.lock = lock;
705            this.c = c;
706        }
872  
873 <        public synchronized void run() {
874 <            lock.lock();
710 <            lockStarted = true;
711 <
712 <            while (!canAwake) {
713 <                c.awaitUninterruptibly();
714 <            }
873 >        awaitTermination(t1);
874 >        awaitTermination(t2);
875  
876 <            interrupted = isInterrupted();
717 <            lock.unlock();
718 <        }
876 >        assertHasNoWaiters(lock, c);
877      }
878  
879      /**
880 <     * awaitUninterruptibly doesn't abort on interrupt
880 >     * awaitUninterruptibly is uninterruptible
881       */
882 <    public void testAwaitUninterruptibly() throws InterruptedException {
883 <        final ReentrantLock lock = new ReentrantLock();
882 >    public void testAwaitUninterruptibly()      { testAwaitUninterruptibly(false); }
883 >    public void testAwaitUninterruptibly_fair() { testAwaitUninterruptibly(true); }
884 >    public void testAwaitUninterruptibly(boolean fair) {
885 >        final ReentrantLock lock = new ReentrantLock(fair);
886          final Condition c = lock.newCondition();
887 <        UninterruptibleThread thread = new UninterruptibleThread(lock, c);
887 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(2);
888  
889 <        thread.start();
889 >        Thread t1 = newStartedThread(new CheckedRunnable() {
890 >            public void realRun() {
891 >                // Interrupt before awaitUninterruptibly
892 >                lock.lock();
893 >                pleaseInterrupt.countDown();
894 >                Thread.currentThread().interrupt();
895 >                c.awaitUninterruptibly();
896 >                assertTrue(Thread.interrupted());
897 >                lock.unlock();
898 >            }});
899  
900 <        while (!thread.lockStarted) {
901 <            Thread.sleep(100);
902 <        }
900 >        Thread t2 = newStartedThread(new CheckedRunnable() {
901 >            public void realRun() {
902 >                // Interrupt during awaitUninterruptibly
903 >                lock.lock();
904 >                pleaseInterrupt.countDown();
905 >                c.awaitUninterruptibly();
906 >                assertTrue(Thread.interrupted());
907 >                lock.unlock();
908 >            }});
909  
910 +        await(pleaseInterrupt);
911          lock.lock();
912 <        try {
913 <            thread.interrupt();
738 <            thread.canAwake = true;
739 <            c.signal();
740 <        } finally {
741 <            lock.unlock();
742 <        }
912 >        lock.unlock();
913 >        t2.interrupt();
914  
915 <        thread.join();
916 <        assertTrue(thread.interrupted);
746 <        assertFalse(thread.isAlive());
747 <    }
915 >        assertThreadStaysAlive(t1);
916 >        assertTrue(t2.isAlive());
917  
918 <    /**
919 <     * await is interruptible
920 <     */
752 <    public void testAwait_Interrupt() throws InterruptedException {
753 <        final ReentrantLock lock = new ReentrantLock();
754 <        final Condition c = lock.newCondition();
755 <        Thread t = new Thread(new CheckedInterruptedRunnable() {
756 <            public void realRun() throws InterruptedException {
757 <                lock.lock();
758 <                c.await();
759 <            }});
918 >        lock.lock();
919 >        c.signalAll();
920 >        lock.unlock();
921  
922 <        t.start();
923 <        Thread.sleep(SHORT_DELAY_MS);
763 <        t.interrupt();
764 <        t.join(SHORT_DELAY_MS);
765 <        assertFalse(t.isAlive());
922 >        awaitTermination(t1);
923 >        awaitTermination(t2);
924      }
925  
926      /**
927 <     * awaitNanos is interruptible
927 >     * await/awaitNanos/awaitUntil is interruptible
928       */
929 <    public void testAwaitNanos_Interrupt() throws InterruptedException {
930 <        final ReentrantLock lock = new ReentrantLock();
929 >    public void testInterruptible_await()           { testInterruptible(false, AwaitMethod.await); }
930 >    public void testInterruptible_await_fair()      { testInterruptible(true,  AwaitMethod.await); }
931 >    public void testInterruptible_awaitTimed()      { testInterruptible(false, AwaitMethod.awaitTimed); }
932 >    public void testInterruptible_awaitTimed_fair() { testInterruptible(true,  AwaitMethod.awaitTimed); }
933 >    public void testInterruptible_awaitNanos()      { testInterruptible(false, AwaitMethod.awaitNanos); }
934 >    public void testInterruptible_awaitNanos_fair() { testInterruptible(true,  AwaitMethod.awaitNanos); }
935 >    public void testInterruptible_awaitUntil()      { testInterruptible(false, AwaitMethod.awaitUntil); }
936 >    public void testInterruptible_awaitUntil_fair() { testInterruptible(true,  AwaitMethod.awaitUntil); }
937 >    public void testInterruptible(boolean fair, final AwaitMethod awaitMethod) {
938 >        final PublicReentrantLock lock =
939 >            new PublicReentrantLock(fair);
940          final Condition c = lock.newCondition();
941 <        Thread t = new Thread(new CheckedInterruptedRunnable() {
941 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
942 >        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
943              public void realRun() throws InterruptedException {
944                  lock.lock();
945 <                c.awaitNanos(MILLISECONDS.toNanos(LONG_DELAY_MS));
945 >                assertLockedByMoi(lock);
946 >                assertHasNoWaiters(lock, c);
947 >                pleaseInterrupt.countDown();
948 >                try {
949 >                    await(c, awaitMethod);
950 >                } finally {
951 >                    assertLockedByMoi(lock);
952 >                    assertHasNoWaiters(lock, c);
953 >                    lock.unlock();
954 >                    assertFalse(Thread.interrupted());
955 >                }
956              }});
957  
958 <        t.start();
959 <        Thread.sleep(SHORT_DELAY_MS);
958 >        await(pleaseInterrupt);
959 >        assertHasWaiters(lock, c, t);
960          t.interrupt();
961 <        t.join(SHORT_DELAY_MS);
962 <        assertFalse(t.isAlive());
961 >        awaitTermination(t);
962 >        assertNotLocked(lock);
963      }
964  
965      /**
966 <     * awaitUntil is interruptible
966 >     * signalAll wakes up all threads
967       */
968 <    public void testAwaitUntil_Interrupt() throws InterruptedException {
969 <        final ReentrantLock lock = new ReentrantLock();
968 >    public void testSignalAll_await()           { testSignalAll(false, AwaitMethod.await); }
969 >    public void testSignalAll_await_fair()      { testSignalAll(true,  AwaitMethod.await); }
970 >    public void testSignalAll_awaitTimed()      { testSignalAll(false, AwaitMethod.awaitTimed); }
971 >    public void testSignalAll_awaitTimed_fair() { testSignalAll(true,  AwaitMethod.awaitTimed); }
972 >    public void testSignalAll_awaitNanos()      { testSignalAll(false, AwaitMethod.awaitNanos); }
973 >    public void testSignalAll_awaitNanos_fair() { testSignalAll(true,  AwaitMethod.awaitNanos); }
974 >    public void testSignalAll_awaitUntil()      { testSignalAll(false, AwaitMethod.awaitUntil); }
975 >    public void testSignalAll_awaitUntil_fair() { testSignalAll(true,  AwaitMethod.awaitUntil); }
976 >    public void testSignalAll(boolean fair, final AwaitMethod awaitMethod) {
977 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
978          final Condition c = lock.newCondition();
979 <        Thread t = new Thread(new CheckedInterruptedRunnable() {
979 >        final CountDownLatch pleaseSignal = new CountDownLatch(2);
980 >        class Awaiter extends CheckedRunnable {
981              public void realRun() throws InterruptedException {
982                  lock.lock();
983 <                java.util.Date d = new java.util.Date();
984 <                c.awaitUntil(new java.util.Date(d.getTime() + 10000));
985 <            }});
983 >                pleaseSignal.countDown();
984 >                await(c, awaitMethod);
985 >                lock.unlock();
986 >            }
987 >        }
988  
989 <        t.start();
990 <        Thread.sleep(SHORT_DELAY_MS);
991 <        t.interrupt();
992 <        t.join(SHORT_DELAY_MS);
993 <        assertFalse(t.isAlive());
989 >        Thread t1 = newStartedThread(new Awaiter());
990 >        Thread t2 = newStartedThread(new Awaiter());
991 >
992 >        await(pleaseSignal);
993 >        lock.lock();
994 >        assertHasWaiters(lock, c, t1, t2);
995 >        c.signalAll();
996 >        assertHasNoWaiters(lock, c);
997 >        lock.unlock();
998 >        awaitTermination(t1);
999 >        awaitTermination(t2);
1000      }
1001  
1002      /**
1003 <     * signalAll wakes up all threads
1003 >     * signal wakes up waiting threads in FIFO order
1004       */
1005 <    public void testSignalAll() throws InterruptedException {
1006 <        final ReentrantLock lock = new ReentrantLock();
1005 >    public void testSignalWakesFifo()      { testSignalWakesFifo(false); }
1006 >    public void testSignalWakesFifo_fair() { testSignalWakesFifo(true); }
1007 >    public void testSignalWakesFifo(boolean fair) {
1008 >        final PublicReentrantLock lock =
1009 >            new PublicReentrantLock(fair);
1010          final Condition c = lock.newCondition();
1011 <        Thread t1 = new Thread(new CheckedRunnable() {
1011 >        final CountDownLatch locked1 = new CountDownLatch(1);
1012 >        final CountDownLatch locked2 = new CountDownLatch(1);
1013 >        Thread t1 = newStartedThread(new CheckedRunnable() {
1014              public void realRun() throws InterruptedException {
1015                  lock.lock();
1016 +                locked1.countDown();
1017                  c.await();
1018                  lock.unlock();
1019              }});
1020  
1021 <        Thread t2 = new Thread(new CheckedRunnable() {
1021 >        await(locked1);
1022 >
1023 >        Thread t2 = newStartedThread(new CheckedRunnable() {
1024              public void realRun() throws InterruptedException {
1025                  lock.lock();
1026 +                locked2.countDown();
1027                  c.await();
1028                  lock.unlock();
1029              }});
1030  
1031 <        t1.start();
1032 <        t2.start();
829 <        Thread.sleep(SHORT_DELAY_MS);
1031 >        await(locked2);
1032 >
1033          lock.lock();
1034 <        c.signalAll();
1034 >        assertHasWaiters(lock, c, t1, t2);
1035 >        assertFalse(lock.hasQueuedThreads());
1036 >        c.signal();
1037 >        assertHasWaiters(lock, c, t2);
1038 >        assertTrue(lock.hasQueuedThread(t1));
1039 >        assertFalse(lock.hasQueuedThread(t2));
1040 >        c.signal();
1041 >        assertHasNoWaiters(lock, c);
1042 >        assertTrue(lock.hasQueuedThread(t1));
1043 >        assertTrue(lock.hasQueuedThread(t2));
1044          lock.unlock();
1045 <        t1.join(SHORT_DELAY_MS);
1046 <        t2.join(SHORT_DELAY_MS);
835 <        assertFalse(t1.isAlive());
836 <        assertFalse(t2.isAlive());
1045 >        awaitTermination(t1);
1046 >        awaitTermination(t2);
1047      }
1048  
1049      /**
1050       * await after multiple reentrant locking preserves lock count
1051       */
1052 <    public void testAwaitLockCount() throws InterruptedException {
1053 <        final ReentrantLock lock = new ReentrantLock();
1052 >    public void testAwaitLockCount()      { testAwaitLockCount(false); }
1053 >    public void testAwaitLockCount_fair() { testAwaitLockCount(true); }
1054 >    public void testAwaitLockCount(boolean fair) {
1055 >        final PublicReentrantLock lock = new PublicReentrantLock(fair);
1056          final Condition c = lock.newCondition();
1057 <        Thread t1 = new Thread(new CheckedRunnable() {
1057 >        final CountDownLatch pleaseSignal = new CountDownLatch(2);
1058 >        Thread t1 = newStartedThread(new CheckedRunnable() {
1059              public void realRun() throws InterruptedException {
1060                  lock.lock();
1061 <                threadAssertEquals(1, lock.getHoldCount());
1061 >                assertLockedByMoi(lock);
1062 >                assertEquals(1, lock.getHoldCount());
1063 >                pleaseSignal.countDown();
1064                  c.await();
1065 <                threadAssertEquals(1, lock.getHoldCount());
1065 >                assertLockedByMoi(lock);
1066 >                assertEquals(1, lock.getHoldCount());
1067                  lock.unlock();
1068              }});
1069  
1070 <        Thread t2 = new Thread(new CheckedRunnable() {
1070 >        Thread t2 = newStartedThread(new CheckedRunnable() {
1071              public void realRun() throws InterruptedException {
1072                  lock.lock();
1073                  lock.lock();
1074 <                threadAssertEquals(2, lock.getHoldCount());
1074 >                assertLockedByMoi(lock);
1075 >                assertEquals(2, lock.getHoldCount());
1076 >                pleaseSignal.countDown();
1077                  c.await();
1078 <                threadAssertEquals(2, lock.getHoldCount());
1078 >                assertLockedByMoi(lock);
1079 >                assertEquals(2, lock.getHoldCount());
1080                  lock.unlock();
1081                  lock.unlock();
1082              }});
1083  
1084 <        t1.start();
866 <        t2.start();
867 <        Thread.sleep(SHORT_DELAY_MS);
1084 >        await(pleaseSignal);
1085          lock.lock();
1086 +        assertHasWaiters(lock, c, t1, t2);
1087 +        assertEquals(1, lock.getHoldCount());
1088          c.signalAll();
1089 +        assertHasNoWaiters(lock, c);
1090          lock.unlock();
1091 <        t1.join(SHORT_DELAY_MS);
1092 <        t2.join(SHORT_DELAY_MS);
873 <        assertFalse(t1.isAlive());
874 <        assertFalse(t2.isAlive());
1091 >        awaitTermination(t1);
1092 >        awaitTermination(t2);
1093      }
1094  
1095      /**
1096       * A serialized lock deserializes as unlocked
1097       */
1098 <    public void testSerialization() throws Exception {
1099 <        ReentrantLock l = new ReentrantLock();
1100 <        l.lock();
1101 <        l.unlock();
1102 <
1103 <        ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
1104 <        ObjectOutputStream out =
1105 <            new ObjectOutputStream(new BufferedOutputStream(bout));
1106 <        out.writeObject(l);
1107 <        out.close();
1108 <
1109 <        ByteArrayInputStream bin =
1110 <            new ByteArrayInputStream(bout.toByteArray());
1111 <        ObjectInputStream in =
1112 <            new ObjectInputStream(new BufferedInputStream(bin));
1113 <        ReentrantLock r = (ReentrantLock) in.readObject();
1114 <        r.lock();
1115 <        r.unlock();
1098 >    public void testSerialization()      { testSerialization(false); }
1099 >    public void testSerialization_fair() { testSerialization(true); }
1100 >    public void testSerialization(boolean fair) {
1101 >        ReentrantLock lock = new ReentrantLock(fair);
1102 >        lock.lock();
1103 >
1104 >        ReentrantLock clone = serialClone(lock);
1105 >        assertEquals(lock.isFair(), clone.isFair());
1106 >        assertTrue(lock.isLocked());
1107 >        assertFalse(clone.isLocked());
1108 >        assertEquals(1, lock.getHoldCount());
1109 >        assertEquals(0, clone.getHoldCount());
1110 >        clone.lock();
1111 >        clone.lock();
1112 >        assertTrue(clone.isLocked());
1113 >        assertEquals(2, clone.getHoldCount());
1114 >        assertEquals(1, lock.getHoldCount());
1115 >        clone.unlock();
1116 >        clone.unlock();
1117 >        assertTrue(lock.isLocked());
1118 >        assertFalse(clone.isLocked());
1119      }
1120  
1121      /**
1122       * toString indicates current lock state
1123       */
1124 <    public void testToString() {
1125 <        ReentrantLock lock = new ReentrantLock();
1126 <        String us = lock.toString();
1127 <        assertTrue(us.indexOf("Unlocked") >= 0);
1124 >    public void testToString()      { testToString(false); }
1125 >    public void testToString_fair() { testToString(true); }
1126 >    public void testToString(boolean fair) {
1127 >        ReentrantLock lock = new ReentrantLock(fair);
1128 >        assertTrue(lock.toString().contains("Unlocked"));
1129          lock.lock();
1130 <        String ls = lock.toString();
1131 <        assertTrue(ls.indexOf("Locked") >= 0);
1130 >        assertTrue(lock.toString().contains("Locked"));
1131 >        lock.unlock();
1132 >        assertTrue(lock.toString().contains("Unlocked"));
1133      }
911
1134   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines