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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines