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

Comparing jsr166/src/test/tck/AbstractQueuedSynchronizerTest.java (file contents):
Revision 1.15 by dl, Sat Jan 10 20:37:20 2004 UTC vs.
Revision 1.69 by jsr166, Wed Aug 14 23:06:11 2019 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
5 < * Other contributors include Andrew Wright, Jeffrey Hayes,
6 < * Pat Fisher, Mike Judd.
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 static java.util.concurrent.TimeUnit.MILLISECONDS;
10 + import static java.util.concurrent.TimeUnit.NANOSECONDS;
11  
12 < import junit.framework.*;
13 < import java.util.*;
14 < import java.util.concurrent.*;
15 < import java.util.concurrent.locks.*;
16 < import java.io.*;
12 > import java.util.ArrayList;
13 > import java.util.Arrays;
14 > import java.util.Collection;
15 > import java.util.HashSet;
16 > import java.util.concurrent.locks.AbstractQueuedSynchronizer;
17 > import java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject;
18  
19 + import junit.framework.Test;
20 + import junit.framework.TestSuite;
21 +
22 + @SuppressWarnings("WaitNotInLoop") // we implement spurious-wakeup freedom
23   public class AbstractQueuedSynchronizerTest 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(AbstractQueuedSynchronizerTest.class);
29      }
30  
31      /**
32 <     * A simple mutex class, adapted from the
33 <     * AbstractQueuedSynchronizer javadoc.  Exclusive acquire tests
34 <     * exercise this as a sample user extension.  Other
35 <     * methods/features of AbstractQueuedSynchronizerTest are tested
36 <     * via other test classes, including those for ReentrantLock,
37 <     * ReentrantReadWriteLock, and Semaphore
32 >     * A simple mutex class, adapted from the class javadoc.  Exclusive
33 >     * acquire tests exercise this as a sample user extension.  Other
34 >     * methods/features of AbstractQueuedSynchronizer are tested via
35 >     * other test classes, including those for ReentrantLock,
36 >     * ReentrantReadWriteLock, and Semaphore.
37 >     *
38 >     * Unlike the javadoc sample, we don't track owner thread via
39 >     * AbstractOwnableSynchronizer methods.
40       */
41      static class Mutex extends AbstractQueuedSynchronizer {
42 <        public boolean isLocked() { return getState() == 1; }
43 <        
44 <        public boolean tryAcquireExclusive(int acquires) {
45 <            assertTrue(acquires == 1);
46 <            return compareAndSetState(0, 1);
47 <        }
48 <        
49 <        public boolean tryReleaseExclusive(int releases) {
50 <            setState(0);
42 >        /** An eccentric value for locked synchronizer state. */
43 >        static final int LOCKED = (1 << 31) | (1 << 15);
44 >
45 >        static final int UNLOCKED = 0;
46 >
47 >        /** Owner thread is untracked, so this is really just isLocked(). */
48 >        @Override public boolean isHeldExclusively() {
49 >            int state = getState();
50 >            assertTrue(state == UNLOCKED || state == LOCKED);
51 >            return state == LOCKED;
52 >        }
53 >
54 >        @Override protected boolean tryAcquire(int acquires) {
55 >            assertEquals(LOCKED, acquires);
56 >            return compareAndSetState(UNLOCKED, LOCKED);
57 >        }
58 >
59 >        @Override protected boolean tryRelease(int releases) {
60 >            if (getState() != LOCKED) throw new IllegalMonitorStateException();
61 >            assertEquals(LOCKED, releases);
62 >            setState(UNLOCKED);
63              return true;
64          }
65 <        
66 <        public void checkConditionAccess(Thread thread) {
67 <            if (getState() == 0) throw new IllegalMonitorStateException();
65 >
66 >        public boolean tryAcquireNanos(long nanos) throws InterruptedException {
67 >            return tryAcquireNanos(LOCKED, nanos);
68 >        }
69 >
70 >        public boolean tryAcquire() {
71 >            return tryAcquire(LOCKED);
72          }
73 <        
74 <        public AbstractQueuedSynchronizer.ConditionObject newCondition() { return new AbstractQueuedSynchronizer.ConditionObject(); }
75 <        
76 <        public void lock() {
77 <            acquireExclusiveUninterruptibly(1);
73 >
74 >        public boolean tryRelease() {
75 >            return tryRelease(LOCKED);
76 >        }
77 >
78 >        public void acquire() {
79 >            acquire(LOCKED);
80          }
81  
82 +        public void acquireInterruptibly() throws InterruptedException {
83 +            acquireInterruptibly(LOCKED);
84 +        }
85 +
86 +        public void release() {
87 +            release(LOCKED);
88 +        }
89 +
90 +        /** Faux-Implements Lock.newCondition(). */
91 +        public ConditionObject newCondition() {
92 +            return new ConditionObject();
93 +        }
94      }
95  
57    
96      /**
97 <     * A simple latch class, to test shared mode.
97 >     * A minimal latch class, to test shared mode.
98       */
99 <    static class BooleanLatch extends AbstractQueuedSynchronizer {
99 >    static class BooleanLatch extends AbstractQueuedSynchronizer {
100          public boolean isSignalled() { return getState() != 0; }
101  
102          public int tryAcquireShared(int ignore) {
103 <            return isSignalled()? 1 : -1;
103 >            return isSignalled() ? 1 : -1;
104          }
105 <        
105 >
106          public boolean tryReleaseShared(int ignore) {
107              setState(1);
108              return true;
# Line 72 | Line 110 | public class AbstractQueuedSynchronizerT
110      }
111  
112      /**
113 <     * A runnable calling acquireExclusiveInterruptibly
113 >     * A runnable calling acquireInterruptibly that does not expect to
114 >     * be interrupted.
115       */
116 <    class InterruptibleLockRunnable implements Runnable {
117 <        final Mutex lock;
118 <        InterruptibleLockRunnable(Mutex l) { lock = l; }
119 <        public void run() {
120 <            try {
121 <                lock.acquireExclusiveInterruptibly(1);
122 <            } catch(InterruptedException success){}
116 >    class InterruptibleSyncRunnable extends CheckedRunnable {
117 >        final Mutex sync;
118 >        InterruptibleSyncRunnable(Mutex sync) { this.sync = sync; }
119 >        public void realRun() throws InterruptedException {
120 >            sync.acquireInterruptibly();
121 >        }
122 >    }
123 >
124 >    /**
125 >     * A runnable calling acquireInterruptibly that expects to be
126 >     * interrupted.
127 >     */
128 >    class InterruptedSyncRunnable extends CheckedInterruptedRunnable {
129 >        final Mutex sync;
130 >        InterruptedSyncRunnable(Mutex sync) { this.sync = sync; }
131 >        public void realRun() throws InterruptedException {
132 >            sync.acquireInterruptibly();
133          }
134      }
135  
136 +    /** A constant to clarify calls to checking methods below. */
137 +    static final Thread[] NO_THREADS = new Thread[0];
138  
139      /**
140 <     * A runnable calling acquireExclusiveInterruptibly that expects to be
90 <     * interrupted
140 >     * Spin-waits until sync.isQueued(t) becomes true.
141       */
142 <    class InterruptedLockRunnable implements Runnable {
143 <        final Mutex lock;
144 <        InterruptedLockRunnable(Mutex l) { lock = l; }
145 <        public void run() {
146 <            try {
147 <                lock.acquireExclusiveInterruptibly(1);
98 <                threadShouldThrow();
99 <            } catch(InterruptedException success){}
142 >    void waitForQueuedThread(AbstractQueuedSynchronizer sync, Thread t) {
143 >        long startTime = System.nanoTime();
144 >        while (!sync.isQueued(t)) {
145 >            if (millisElapsedSince(startTime) > LONG_DELAY_MS)
146 >                throw new AssertionError("timed out");
147 >            Thread.yield();
148          }
149 +        assertTrue(t.isAlive());
150      }
151 <    
151 >
152      /**
153 <     * acquireExclusiveUninterruptiblying an releaseExclusiveed lock succeeds
153 >     * Checks that sync has exactly the given queued threads.
154       */
155 <    public void testAcquireExclusiveUninterruptibly() {
156 <        Mutex rl = new Mutex();
157 <        rl.acquireExclusiveUninterruptibly(1);
158 <        assertTrue(rl.isLocked());
159 <        rl.releaseExclusive(1);
155 >    void assertHasQueuedThreads(AbstractQueuedSynchronizer sync,
156 >                                Thread... expected) {
157 >        Collection<Thread> actual = sync.getQueuedThreads();
158 >        assertEquals(expected.length > 0, sync.hasQueuedThreads());
159 >        assertEquals(expected.length, sync.getQueueLength());
160 >        assertEquals(expected.length, actual.size());
161 >        assertEquals(expected.length == 0, actual.isEmpty());
162 >        assertEquals(new HashSet<Thread>(actual),
163 >                     new HashSet<Thread>(Arrays.asList(expected)));
164      }
165  
166      /**
167 <     * tryAcquireExclusive on an releaseExclusiveed lock succeeds
167 >     * Checks that sync has exactly the given (exclusive) queued threads.
168       */
169 <    public void testTryAcquireExclusive() {
170 <        Mutex rl = new Mutex();
171 <        assertTrue(rl.tryAcquireExclusive(1));
172 <        assertTrue(rl.isLocked());
173 <        rl.releaseExclusive(1);
169 >    void assertHasExclusiveQueuedThreads(AbstractQueuedSynchronizer sync,
170 >                                         Thread... expected) {
171 >        assertHasQueuedThreads(sync, expected);
172 >        assertEquals(new HashSet<Thread>(sync.getExclusiveQueuedThreads()),
173 >                     new HashSet<Thread>(sync.getQueuedThreads()));
174 >        assertEquals(0, sync.getSharedQueuedThreads().size());
175 >        assertTrue(sync.getSharedQueuedThreads().isEmpty());
176 >    }
177 >
178 >    /**
179 >     * Checks that sync has exactly the given (shared) queued threads.
180 >     */
181 >    void assertHasSharedQueuedThreads(AbstractQueuedSynchronizer sync,
182 >                                      Thread... expected) {
183 >        assertHasQueuedThreads(sync, expected);
184 >        assertEquals(new HashSet<Thread>(sync.getSharedQueuedThreads()),
185 >                     new HashSet<Thread>(sync.getQueuedThreads()));
186 >        assertEquals(0, sync.getExclusiveQueuedThreads().size());
187 >        assertTrue(sync.getExclusiveQueuedThreads().isEmpty());
188 >    }
189 >
190 >    /**
191 >     * Checks that condition c has exactly the given waiter threads,
192 >     * after acquiring mutex.
193 >     */
194 >    void assertHasWaitersUnlocked(Mutex sync, ConditionObject c,
195 >                                 Thread... threads) {
196 >        sync.acquire();
197 >        assertHasWaitersLocked(sync, c, threads);
198 >        sync.release();
199 >    }
200 >
201 >    /**
202 >     * Checks that condition c has exactly the given waiter threads.
203 >     */
204 >    void assertHasWaitersLocked(Mutex sync, ConditionObject c,
205 >                                Thread... threads) {
206 >        assertEquals(threads.length > 0, sync.hasWaiters(c));
207 >        assertEquals(threads.length, sync.getWaitQueueLength(c));
208 >        assertEquals(threads.length == 0, sync.getWaitingThreads(c).isEmpty());
209 >        assertEquals(threads.length, sync.getWaitingThreads(c).size());
210 >        assertEquals(new HashSet<Thread>(sync.getWaitingThreads(c)),
211 >                     new HashSet<Thread>(Arrays.asList(threads)));
212 >    }
213 >
214 >    enum AwaitMethod { await, awaitTimed, awaitNanos, awaitUntil }
215 >
216 >    /**
217 >     * Awaits condition using the specified AwaitMethod.
218 >     */
219 >    void await(ConditionObject c, AwaitMethod awaitMethod)
220 >            throws InterruptedException {
221 >        long timeoutMillis = 2 * LONG_DELAY_MS;
222 >        switch (awaitMethod) {
223 >        case await:
224 >            c.await();
225 >            break;
226 >        case awaitTimed:
227 >            assertTrue(c.await(timeoutMillis, MILLISECONDS));
228 >            break;
229 >        case awaitNanos:
230 >            long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
231 >            long nanosRemaining = c.awaitNanos(timeoutNanos);
232 >            assertTrue(nanosRemaining > 0);
233 >            break;
234 >        case awaitUntil:
235 >            assertTrue(c.awaitUntil(delayedDate(timeoutMillis)));
236 >            break;
237 >        default:
238 >            throw new AssertionError();
239 >        }
240 >    }
241 >
242 >    /**
243 >     * Checks that awaiting the given condition times out (using the
244 >     * default timeout duration).
245 >     */
246 >    void assertAwaitTimesOut(ConditionObject c, AwaitMethod awaitMethod) {
247 >        final long timeoutMillis = timeoutMillis();
248 >        final long startTime;
249 >        try {
250 >            switch (awaitMethod) {
251 >            case awaitTimed:
252 >                startTime = System.nanoTime();
253 >                assertFalse(c.await(timeoutMillis, MILLISECONDS));
254 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
255 >                break;
256 >            case awaitNanos:
257 >                startTime = System.nanoTime();
258 >                long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
259 >                long nanosRemaining = c.awaitNanos(timeoutNanos);
260 >                assertTrue(nanosRemaining <= 0);
261 >                assertTrue(nanosRemaining > -MILLISECONDS.toNanos(LONG_DELAY_MS));
262 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
263 >                break;
264 >            case awaitUntil:
265 >                // We shouldn't assume that nanoTime and currentTimeMillis
266 >                // use the same time source, so don't use nanoTime here.
267 >                java.util.Date delayedDate = delayedDate(timeoutMillis);
268 >                assertFalse(c.awaitUntil(delayedDate(timeoutMillis)));
269 >                assertTrue(new java.util.Date().getTime() >= delayedDate.getTime());
270 >                break;
271 >            default:
272 >                throw new UnsupportedOperationException();
273 >            }
274 >        } catch (InterruptedException ie) { threadUnexpectedException(ie); }
275 >    }
276 >
277 >    /**
278 >     * isHeldExclusively is false upon construction
279 >     */
280 >    public void testIsHeldExclusively() {
281 >        Mutex sync = new Mutex();
282 >        assertFalse(sync.isHeldExclusively());
283 >    }
284 >
285 >    /**
286 >     * acquiring released sync succeeds
287 >     */
288 >    public void testAcquire() {
289 >        Mutex sync = new Mutex();
290 >        sync.acquire();
291 >        assertTrue(sync.isHeldExclusively());
292 >        sync.release();
293 >        assertFalse(sync.isHeldExclusively());
294 >    }
295 >
296 >    /**
297 >     * tryAcquire on a released sync succeeds
298 >     */
299 >    public void testTryAcquire() {
300 >        Mutex sync = new Mutex();
301 >        assertTrue(sync.tryAcquire());
302 >        assertTrue(sync.isHeldExclusively());
303 >        sync.release();
304 >        assertFalse(sync.isHeldExclusively());
305      }
306  
307      /**
308       * hasQueuedThreads reports whether there are waiting threads
309       */
310 <    public void testhasQueuedThreads() {
311 <        final Mutex lock = new Mutex();
312 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
313 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
314 <        try {
315 <            assertFalse(lock.hasQueuedThreads());
316 <            lock.acquireExclusiveUninterruptibly(1);
317 <            t1.start();
318 <            Thread.sleep(SHORT_DELAY_MS);
319 <            assertTrue(lock.hasQueuedThreads());
320 <            t2.start();
321 <            Thread.sleep(SHORT_DELAY_MS);
322 <            assertTrue(lock.hasQueuedThreads());
323 <            t1.interrupt();
324 <            Thread.sleep(SHORT_DELAY_MS);
325 <            assertTrue(lock.hasQueuedThreads());
326 <            lock.releaseExclusive(1);
143 <            Thread.sleep(SHORT_DELAY_MS);
144 <            assertFalse(lock.hasQueuedThreads());
145 <            t1.join();
146 <            t2.join();
147 <        } catch(Exception e){
148 <            unexpectedException();
149 <        }
150 <    }
310 >    public void testHasQueuedThreads() {
311 >        final Mutex sync = new Mutex();
312 >        assertFalse(sync.hasQueuedThreads());
313 >        sync.acquire();
314 >        Thread t1 = newStartedThread(new InterruptedSyncRunnable(sync));
315 >        waitForQueuedThread(sync, t1);
316 >        assertTrue(sync.hasQueuedThreads());
317 >        Thread t2 = newStartedThread(new InterruptibleSyncRunnable(sync));
318 >        waitForQueuedThread(sync, t2);
319 >        assertTrue(sync.hasQueuedThreads());
320 >        t1.interrupt();
321 >        awaitTermination(t1);
322 >        assertTrue(sync.hasQueuedThreads());
323 >        sync.release();
324 >        awaitTermination(t2);
325 >        assertFalse(sync.hasQueuedThreads());
326 >    }
327  
328      /**
329 <     * isQueued(null) throws NPE
329 >     * isQueued(null) throws NullPointerException
330       */
331 <    public void testIsQueuedNPE() {
332 <        final Mutex lock = new Mutex();
331 >    public void testIsQueuedNPE() {
332 >        final Mutex sync = new Mutex();
333          try {
334 <            lock.isQueued(null);
334 >            sync.isQueued(null);
335              shouldThrow();
336 <        } catch (NullPointerException success) {
161 <        }
336 >        } catch (NullPointerException success) {}
337      }
338  
339      /**
340 <     * isQueued reports whether a thread is queued.
340 >     * isQueued reports whether a thread is queued
341       */
342 <    public void testIsQueued() {
343 <        final Mutex lock = new Mutex();
344 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
345 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
346 <        try {
347 <            assertFalse(lock.isQueued(t1));
348 <            assertFalse(lock.isQueued(t2));
349 <            lock.acquireExclusiveUninterruptibly(1);
350 <            t1.start();
351 <            Thread.sleep(SHORT_DELAY_MS);
352 <            assertTrue(lock.isQueued(t1));
353 <            t2.start();
354 <            Thread.sleep(SHORT_DELAY_MS);
355 <            assertTrue(lock.isQueued(t1));
356 <            assertTrue(lock.isQueued(t2));
357 <            t1.interrupt();
358 <            Thread.sleep(SHORT_DELAY_MS);
359 <            assertFalse(lock.isQueued(t1));
360 <            assertTrue(lock.isQueued(t2));
361 <            lock.releaseExclusive(1);
362 <            Thread.sleep(SHORT_DELAY_MS);
363 <            assertFalse(lock.isQueued(t1));
364 <            assertFalse(lock.isQueued(t2));
365 <            t1.join();
191 <            t2.join();
192 <        } catch(Exception e){
193 <            unexpectedException();
194 <        }
195 <    }
196 <
197 <    /**
198 <     * getFirstQueuedThread returns first waiting thread or null is none
199 <     */
200 <    public void testGetFirstQueuedThread() {
201 <        final Mutex lock = new Mutex();
202 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
203 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
204 <        try {
205 <            assertNull(lock.getFirstQueuedThread());
206 <            lock.acquireExclusiveUninterruptibly(1);
207 <            t1.start();
208 <            Thread.sleep(SHORT_DELAY_MS);
209 <            assertEquals(t1, lock.getFirstQueuedThread());
210 <            t2.start();
211 <            Thread.sleep(SHORT_DELAY_MS);
212 <            assertEquals(t1, lock.getFirstQueuedThread());
213 <            t1.interrupt();
214 <            Thread.sleep(SHORT_DELAY_MS);
215 <            assertEquals(t2, lock.getFirstQueuedThread());
216 <            lock.releaseExclusive(1);
217 <            Thread.sleep(SHORT_DELAY_MS);
218 <            assertNull(lock.getFirstQueuedThread());
219 <            t1.join();
220 <            t2.join();
221 <        } catch(Exception e){
222 <            unexpectedException();
223 <        }
224 <    }
342 >    public void testIsQueued() {
343 >        final Mutex sync = new Mutex();
344 >        Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
345 >        Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
346 >        assertFalse(sync.isQueued(t1));
347 >        assertFalse(sync.isQueued(t2));
348 >        sync.acquire();
349 >        t1.start();
350 >        waitForQueuedThread(sync, t1);
351 >        assertTrue(sync.isQueued(t1));
352 >        assertFalse(sync.isQueued(t2));
353 >        t2.start();
354 >        waitForQueuedThread(sync, t2);
355 >        assertTrue(sync.isQueued(t1));
356 >        assertTrue(sync.isQueued(t2));
357 >        t1.interrupt();
358 >        awaitTermination(t1);
359 >        assertFalse(sync.isQueued(t1));
360 >        assertTrue(sync.isQueued(t2));
361 >        sync.release();
362 >        awaitTermination(t2);
363 >        assertFalse(sync.isQueued(t1));
364 >        assertFalse(sync.isQueued(t2));
365 >    }
366  
367 +    /**
368 +     * getFirstQueuedThread returns first waiting thread or null if none
369 +     */
370 +    public void testGetFirstQueuedThread() {
371 +        final Mutex sync = new Mutex();
372 +        assertNull(sync.getFirstQueuedThread());
373 +        sync.acquire();
374 +        Thread t1 = newStartedThread(new InterruptedSyncRunnable(sync));
375 +        waitForQueuedThread(sync, t1);
376 +        assertEquals(t1, sync.getFirstQueuedThread());
377 +        Thread t2 = newStartedThread(new InterruptibleSyncRunnable(sync));
378 +        waitForQueuedThread(sync, t2);
379 +        assertEquals(t1, sync.getFirstQueuedThread());
380 +        t1.interrupt();
381 +        awaitTermination(t1);
382 +        assertEquals(t2, sync.getFirstQueuedThread());
383 +        sync.release();
384 +        awaitTermination(t2);
385 +        assertNull(sync.getFirstQueuedThread());
386 +    }
387  
388      /**
389       * hasContended reports false if no thread has ever blocked, else true
390       */
391 <    public void testHasContended() {
392 <        final Mutex lock = new Mutex();
393 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
394 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
395 <        try {
396 <            assertFalse(lock.hasContended());
397 <            lock.acquireExclusiveUninterruptibly(1);
398 <            t1.start();
399 <            Thread.sleep(SHORT_DELAY_MS);
400 <            assertTrue(lock.hasContended());
401 <            t2.start();
402 <            Thread.sleep(SHORT_DELAY_MS);
403 <            assertTrue(lock.hasContended());
404 <            t1.interrupt();
405 <            Thread.sleep(SHORT_DELAY_MS);
406 <            assertTrue(lock.hasContended());
407 <            lock.releaseExclusive(1);
408 <            Thread.sleep(SHORT_DELAY_MS);
409 <            assertTrue(lock.hasContended());
410 <            t1.join();
411 <            t2.join();
412 <        } catch(Exception e){
413 <            unexpectedException();
414 <        }
415 <    }
416 <
417 <    /**
418 <     * acquireExclusiveNanos is interruptible.
419 <     */
420 <    public void testInterruptedException2() {
421 <        final Mutex lock = new Mutex();
422 <        lock.acquireExclusiveUninterruptibly(1);
423 <        Thread t = new Thread(new Runnable() {
424 <                public void run() {
425 <                    try {
426 <                        lock.acquireExclusiveNanos(1, MEDIUM_DELAY_MS * 1000 * 1000);
427 <                        threadShouldThrow();
428 <                    } catch(InterruptedException success){}
429 <                }
430 <            });
431 <        try {
432 <            t.start();
433 <            t.interrupt();
434 <        } catch(Exception e){
435 <            unexpectedException();
436 <        }
391 >    public void testHasContended() {
392 >        final Mutex sync = new Mutex();
393 >        assertFalse(sync.hasContended());
394 >        sync.acquire();
395 >        assertFalse(sync.hasContended());
396 >        Thread t1 = newStartedThread(new InterruptedSyncRunnable(sync));
397 >        waitForQueuedThread(sync, t1);
398 >        assertTrue(sync.hasContended());
399 >        Thread t2 = newStartedThread(new InterruptibleSyncRunnable(sync));
400 >        waitForQueuedThread(sync, t2);
401 >        assertTrue(sync.hasContended());
402 >        t1.interrupt();
403 >        awaitTermination(t1);
404 >        assertTrue(sync.hasContended());
405 >        sync.release();
406 >        awaitTermination(t2);
407 >        assertTrue(sync.hasContended());
408 >    }
409 >
410 >    /**
411 >     * getQueuedThreads returns all waiting threads
412 >     */
413 >    public void testGetQueuedThreads() {
414 >        final Mutex sync = new Mutex();
415 >        Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
416 >        Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
417 >        assertHasExclusiveQueuedThreads(sync, NO_THREADS);
418 >        sync.acquire();
419 >        assertHasExclusiveQueuedThreads(sync, NO_THREADS);
420 >        t1.start();
421 >        waitForQueuedThread(sync, t1);
422 >        assertHasExclusiveQueuedThreads(sync, t1);
423 >        assertTrue(sync.getQueuedThreads().contains(t1));
424 >        assertFalse(sync.getQueuedThreads().contains(t2));
425 >        t2.start();
426 >        waitForQueuedThread(sync, t2);
427 >        assertHasExclusiveQueuedThreads(sync, t1, t2);
428 >        assertTrue(sync.getQueuedThreads().contains(t1));
429 >        assertTrue(sync.getQueuedThreads().contains(t2));
430 >        t1.interrupt();
431 >        awaitTermination(t1);
432 >        assertHasExclusiveQueuedThreads(sync, t2);
433 >        sync.release();
434 >        awaitTermination(t2);
435 >        assertHasExclusiveQueuedThreads(sync, NO_THREADS);
436 >    }
437 >
438 >    /**
439 >     * getExclusiveQueuedThreads returns all exclusive waiting threads
440 >     */
441 >    public void testGetExclusiveQueuedThreads() {
442 >        final Mutex sync = new Mutex();
443 >        Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
444 >        Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
445 >        assertHasExclusiveQueuedThreads(sync, NO_THREADS);
446 >        sync.acquire();
447 >        assertHasExclusiveQueuedThreads(sync, NO_THREADS);
448 >        t1.start();
449 >        waitForQueuedThread(sync, t1);
450 >        assertHasExclusiveQueuedThreads(sync, t1);
451 >        assertTrue(sync.getExclusiveQueuedThreads().contains(t1));
452 >        assertFalse(sync.getExclusiveQueuedThreads().contains(t2));
453 >        t2.start();
454 >        waitForQueuedThread(sync, t2);
455 >        assertHasExclusiveQueuedThreads(sync, t1, t2);
456 >        assertTrue(sync.getExclusiveQueuedThreads().contains(t1));
457 >        assertTrue(sync.getExclusiveQueuedThreads().contains(t2));
458 >        t1.interrupt();
459 >        awaitTermination(t1);
460 >        assertHasExclusiveQueuedThreads(sync, t2);
461 >        sync.release();
462 >        awaitTermination(t2);
463 >        assertHasExclusiveQueuedThreads(sync, NO_THREADS);
464 >    }
465 >
466 >    /**
467 >     * getSharedQueuedThreads does not include exclusively waiting threads
468 >     */
469 >    public void testGetSharedQueuedThreads_Exclusive() {
470 >        final Mutex sync = new Mutex();
471 >        assertTrue(sync.getSharedQueuedThreads().isEmpty());
472 >        sync.acquire();
473 >        assertTrue(sync.getSharedQueuedThreads().isEmpty());
474 >        Thread t1 = newStartedThread(new InterruptedSyncRunnable(sync));
475 >        waitForQueuedThread(sync, t1);
476 >        assertTrue(sync.getSharedQueuedThreads().isEmpty());
477 >        Thread t2 = newStartedThread(new InterruptibleSyncRunnable(sync));
478 >        waitForQueuedThread(sync, t2);
479 >        assertTrue(sync.getSharedQueuedThreads().isEmpty());
480 >        t1.interrupt();
481 >        awaitTermination(t1);
482 >        assertTrue(sync.getSharedQueuedThreads().isEmpty());
483 >        sync.release();
484 >        awaitTermination(t2);
485 >        assertTrue(sync.getSharedQueuedThreads().isEmpty());
486      }
487  
278
488      /**
489 <     * TryAcquireExclusive on a locked lock fails
489 >     * getSharedQueuedThreads returns all shared waiting threads
490       */
491 <    public void testTryAcquireExclusiveWhenLocked() {
492 <        final Mutex lock = new Mutex();
493 <        lock.acquireExclusiveUninterruptibly(1);
494 <        Thread t = new Thread(new Runnable() {
495 <                public void run() {
496 <                    threadAssertFalse(lock.tryAcquireExclusive(1));
497 <                }
498 <            });
499 <        try {
500 <            t.start();
501 <            t.join();
502 <            lock.releaseExclusive(1);
503 <        } catch(Exception e){
504 <            unexpectedException();
505 <        }
506 <    }
507 <
508 <    /**
509 <     * acquireExclusiveNanos on a locked lock times out
510 <     */
511 <    public void testAcquireExclusiveNanos_Timeout() {
512 <        final Mutex lock = new Mutex();
513 <        lock.acquireExclusiveUninterruptibly(1);
514 <        Thread t = new Thread(new Runnable() {
515 <                public void run() {
516 <                    try {
517 <                        threadAssertFalse(lock.acquireExclusiveNanos(1, 1000 * 1000));
518 <                    } catch (Exception ex) {
519 <                        threadUnexpectedException();
520 <                    }
521 <                }
522 <            });
523 <        try {
524 <            t.start();
525 <            t.join();
526 <            lock.releaseExclusive(1);
527 <        } catch(Exception e){
528 <            unexpectedException();
529 <        }
530 <    }
531 <    
532 <  
491 >    public void testGetSharedQueuedThreads_Shared() {
492 >        final BooleanLatch l = new BooleanLatch();
493 >        assertHasSharedQueuedThreads(l, NO_THREADS);
494 >        Thread t1 = newStartedThread(new CheckedInterruptedRunnable() {
495 >            public void realRun() throws InterruptedException {
496 >                l.acquireSharedInterruptibly(0);
497 >            }});
498 >        waitForQueuedThread(l, t1);
499 >        assertHasSharedQueuedThreads(l, t1);
500 >        Thread t2 = newStartedThread(new CheckedRunnable() {
501 >            public void realRun() throws InterruptedException {
502 >                l.acquireSharedInterruptibly(0);
503 >            }});
504 >        waitForQueuedThread(l, t2);
505 >        assertHasSharedQueuedThreads(l, t1, t2);
506 >        t1.interrupt();
507 >        awaitTermination(t1);
508 >        assertHasSharedQueuedThreads(l, t2);
509 >        assertTrue(l.releaseShared(0));
510 >        awaitTermination(t2);
511 >        assertHasSharedQueuedThreads(l, NO_THREADS);
512 >    }
513 >
514 >    /**
515 >     * tryAcquireNanos is interruptible
516 >     */
517 >    public void testTryAcquireNanos_Interruptible() {
518 >        final Mutex sync = new Mutex();
519 >        sync.acquire();
520 >        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
521 >            public void realRun() throws InterruptedException {
522 >                sync.tryAcquireNanos(MILLISECONDS.toNanos(2 * LONG_DELAY_MS));
523 >            }});
524 >
525 >        waitForQueuedThread(sync, t);
526 >        t.interrupt();
527 >        awaitTermination(t);
528 >    }
529 >
530 >    /**
531 >     * tryAcquire on exclusively held sync fails
532 >     */
533 >    public void testTryAcquireWhenSynced() {
534 >        final Mutex sync = new Mutex();
535 >        sync.acquire();
536 >        Thread t = newStartedThread(new CheckedRunnable() {
537 >            public void realRun() {
538 >                assertFalse(sync.tryAcquire());
539 >            }});
540 >
541 >        awaitTermination(t);
542 >        sync.release();
543 >    }
544 >
545 >    /**
546 >     * tryAcquireNanos on an exclusively held sync times out
547 >     */
548 >    public void testAcquireNanos_Timeout() {
549 >        final Mutex sync = new Mutex();
550 >        sync.acquire();
551 >        Thread t = newStartedThread(new CheckedRunnable() {
552 >            public void realRun() throws InterruptedException {
553 >                long startTime = System.nanoTime();
554 >                long nanos = MILLISECONDS.toNanos(timeoutMillis());
555 >                assertFalse(sync.tryAcquireNanos(nanos));
556 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
557 >            }});
558 >
559 >        awaitTermination(t);
560 >        sync.release();
561 >    }
562 >
563      /**
564       * getState is true when acquired and false when not
565       */
566      public void testGetState() {
567 <        final Mutex lock = new Mutex();
568 <        lock.acquireExclusiveUninterruptibly(1);
569 <        assertTrue(lock.isLocked());
570 <        lock.releaseExclusive(1);
571 <        assertFalse(lock.isLocked());
572 <        Thread t = new Thread(new Runnable() {
573 <                public void run() {
574 <                    lock.acquireExclusiveUninterruptibly(1);
575 <                    try {
576 <                        Thread.sleep(SMALL_DELAY_MS);
577 <                    }
578 <                    catch(Exception e) {
579 <                        threadUnexpectedException();
580 <                    }
581 <                    lock.releaseExclusive(1);
582 <                }
583 <            });
584 <        try {
585 <            t.start();
586 <            Thread.sleep(SHORT_DELAY_MS);
587 <            assertTrue(lock.isLocked());
349 <            t.join();
350 <            assertFalse(lock.isLocked());
351 <        } catch(Exception e){
352 <            unexpectedException();
353 <        }
567 >        final Mutex sync = new Mutex();
568 >        sync.acquire();
569 >        assertTrue(sync.isHeldExclusively());
570 >        sync.release();
571 >        assertFalse(sync.isHeldExclusively());
572 >
573 >        final BooleanLatch acquired = new BooleanLatch();
574 >        final BooleanLatch done = new BooleanLatch();
575 >        Thread t = newStartedThread(new CheckedRunnable() {
576 >            public void realRun() throws InterruptedException {
577 >                sync.acquire();
578 >                assertTrue(acquired.releaseShared(0));
579 >                done.acquireShared(0);
580 >                sync.release();
581 >            }});
582 >
583 >        acquired.acquireShared(0);
584 >        assertTrue(sync.isHeldExclusively());
585 >        assertTrue(done.releaseShared(0));
586 >        awaitTermination(t);
587 >        assertFalse(sync.isHeldExclusively());
588      }
589  
356
590      /**
591 <     * acquireExclusiveInterruptibly is interruptible.
592 <     */
593 <    public void testAcquireInterruptibly1() {
594 <        final Mutex lock = new Mutex();
595 <        lock.acquireExclusiveUninterruptibly(1);
596 <        Thread t = new Thread(new InterruptedLockRunnable(lock));
597 <        try {
598 <            t.start();
599 <            t.interrupt();
600 <            lock.releaseExclusive(1);
601 <            t.join();
602 <        } catch(Exception e){
603 <            unexpectedException();
604 <        }
605 <    }
606 <
607 <    /**
375 <     * acquireExclusiveInterruptibly succeeds when released, else is interruptible
376 <     */
377 <    public void testAcquireInterruptibly2() {
378 <        final Mutex lock = new Mutex();
379 <        try {
380 <            lock.acquireExclusiveInterruptibly(1);
381 <        } catch(Exception e) {
382 <            unexpectedException();
383 <        }
384 <        Thread t = new Thread(new InterruptedLockRunnable(lock));
385 <        try {
386 <            t.start();
387 <            t.interrupt();
388 <            assertTrue(lock.isLocked());
389 <            t.join();
390 <        } catch(Exception e){
391 <            unexpectedException();
392 <        }
591 >     * acquireInterruptibly succeeds when released, else is interruptible
592 >     */
593 >    public void testAcquireInterruptibly() throws InterruptedException {
594 >        final Mutex sync = new Mutex();
595 >        final BooleanLatch threadStarted = new BooleanLatch();
596 >        sync.acquireInterruptibly();
597 >        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
598 >            public void realRun() throws InterruptedException {
599 >                assertTrue(threadStarted.releaseShared(0));
600 >                sync.acquireInterruptibly();
601 >            }});
602 >
603 >        threadStarted.acquireShared(0);
604 >        waitForQueuedThread(sync, t);
605 >        t.interrupt();
606 >        awaitTermination(t);
607 >        assertTrue(sync.isHeldExclusively());
608      }
609  
610      /**
611 <     * owns is true for a condition created by lock else false
611 >     * owns is true for a condition created by sync else false
612       */
613      public void testOwns() {
614 <        final Mutex lock = new Mutex();
615 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
616 <        final Mutex lock2 = new Mutex();
617 <        assertTrue(lock.owns(c));
618 <        assertFalse(lock2.owns(c));
614 >        final Mutex sync = new Mutex();
615 >        final ConditionObject c = sync.newCondition();
616 >        final Mutex sync2 = new Mutex();
617 >        assertTrue(sync.owns(c));
618 >        assertFalse(sync2.owns(c));
619      }
620  
621      /**
622 <     * Calling await without holding lock throws IllegalMonitorStateException
622 >     * Calling await without holding sync throws IllegalMonitorStateException
623       */
624 <    public void testAwait_IllegalMonitor() {
625 <        final Mutex lock = new Mutex();
626 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
627 <        try {
628 <            c.await();
629 <            shouldThrow();
630 <        }
631 <        catch (IllegalMonitorStateException success) {
632 <        }
633 <        catch (Exception ex) {
634 <            unexpectedException();
624 >    public void testAwait_IMSE() {
625 >        final Mutex sync = new Mutex();
626 >        final ConditionObject c = sync.newCondition();
627 >        for (AwaitMethod awaitMethod : AwaitMethod.values()) {
628 >            long startTime = System.nanoTime();
629 >            try {
630 >                await(c, awaitMethod);
631 >                shouldThrow();
632 >            } catch (IllegalMonitorStateException success) {
633 >            } catch (InterruptedException e) { threadUnexpectedException(e); }
634 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
635          }
636      }
637  
638      /**
639 <     * Calling signal without holding lock throws IllegalMonitorStateException
639 >     * Calling signal without holding sync throws IllegalMonitorStateException
640       */
641 <    public void testSignal_IllegalMonitor() {
642 <        final Mutex lock = new Mutex();
643 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
641 >    public void testSignal_IMSE() {
642 >        final Mutex sync = new Mutex();
643 >        final ConditionObject c = sync.newCondition();
644          try {
645              c.signal();
646              shouldThrow();
647 <        }
648 <        catch (IllegalMonitorStateException success) {
434 <        }
435 <        catch (Exception ex) {
436 <            unexpectedException();
437 <        }
438 <    }
439 <
440 <    /**
441 <     * awaitNanos without a signal times out
442 <     */
443 <    public void testAwaitNanos_Timeout() {
444 <        final Mutex lock = new Mutex();
445 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
446 <        try {
447 <            lock.acquireExclusiveUninterruptibly(1);
448 <            long t = c.awaitNanos(100);
449 <            assertTrue(t <= 0);
450 <            lock.releaseExclusive(1);
451 <        }
452 <        catch (Exception ex) {
453 <            unexpectedException();
454 <        }
647 >        } catch (IllegalMonitorStateException success) {}
648 >        assertHasWaitersUnlocked(sync, c, NO_THREADS);
649      }
650  
651      /**
652 <     *  timed await without a signal times out
652 >     * Calling signalAll without holding sync throws IllegalMonitorStateException
653       */
654 <    public void testAwait_Timeout() {
655 <        final Mutex lock = new Mutex();
656 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
654 >    public void testSignalAll_IMSE() {
655 >        final Mutex sync = new Mutex();
656 >        final ConditionObject c = sync.newCondition();
657          try {
658 <            lock.acquireExclusiveUninterruptibly(1);
659 <            assertFalse(c.await(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
660 <            lock.releaseExclusive(1);
467 <        }
468 <        catch (Exception ex) {
469 <            unexpectedException();
470 <        }
658 >            c.signalAll();
659 >            shouldThrow();
660 >        } catch (IllegalMonitorStateException success) {}
661      }
662  
663      /**
664 <     * awaitUntil without a signal times out
664 >     * await/awaitNanos/awaitUntil without a signal times out
665       */
666 <    public void testAwaitUntil_Timeout() {
667 <        final Mutex lock = new Mutex();
668 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
669 <        try {
670 <            lock.acquireExclusiveUninterruptibly(1);
671 <            java.util.Date d = new java.util.Date();
672 <            assertFalse(c.awaitUntil(new java.util.Date(d.getTime() + 10)));
673 <            lock.releaseExclusive(1);
674 <        }
485 <        catch (Exception ex) {
486 <            unexpectedException();
487 <        }
666 >    public void testAwaitTimed_Timeout() { testAwait_Timeout(AwaitMethod.awaitTimed); }
667 >    public void testAwaitNanos_Timeout() { testAwait_Timeout(AwaitMethod.awaitNanos); }
668 >    public void testAwaitUntil_Timeout() { testAwait_Timeout(AwaitMethod.awaitUntil); }
669 >    public void testAwait_Timeout(AwaitMethod awaitMethod) {
670 >        final Mutex sync = new Mutex();
671 >        final ConditionObject c = sync.newCondition();
672 >        sync.acquire();
673 >        assertAwaitTimesOut(c, awaitMethod);
674 >        sync.release();
675      }
676  
677      /**
678 <     * await returns when signalled
679 <     */
680 <    public void testAwait() {
681 <        final Mutex lock = new Mutex();
682 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
683 <        Thread t = new Thread(new Runnable() {
684 <                public void run() {
685 <                    try {
686 <                        lock.acquireExclusiveUninterruptibly(1);
687 <                        c.await();
688 <                        lock.releaseExclusive(1);
689 <                    }
690 <                    catch(InterruptedException e) {
691 <                        threadUnexpectedException();
692 <                    }
693 <                }
694 <            });
695 <
696 <        try {
697 <            t.start();
698 <            Thread.sleep(SHORT_DELAY_MS);
699 <            lock.acquireExclusiveUninterruptibly(1);
700 <            c.signal();
701 <            lock.releaseExclusive(1);
702 <            t.join(SHORT_DELAY_MS);
703 <            assertFalse(t.isAlive());
704 <        }
518 <        catch (Exception ex) {
519 <            unexpectedException();
520 <        }
678 >     * await/awaitNanos/awaitUntil returns when signalled
679 >     */
680 >    public void testSignal_await()      { testSignal(AwaitMethod.await); }
681 >    public void testSignal_awaitTimed() { testSignal(AwaitMethod.awaitTimed); }
682 >    public void testSignal_awaitNanos() { testSignal(AwaitMethod.awaitNanos); }
683 >    public void testSignal_awaitUntil() { testSignal(AwaitMethod.awaitUntil); }
684 >    public void testSignal(final AwaitMethod awaitMethod) {
685 >        final Mutex sync = new Mutex();
686 >        final ConditionObject c = sync.newCondition();
687 >        final BooleanLatch acquired = new BooleanLatch();
688 >        Thread t = newStartedThread(new CheckedRunnable() {
689 >            public void realRun() throws InterruptedException {
690 >                sync.acquire();
691 >                assertTrue(acquired.releaseShared(0));
692 >                await(c, awaitMethod);
693 >                sync.release();
694 >            }});
695 >
696 >        acquired.acquireShared(0);
697 >        sync.acquire();
698 >        assertHasWaitersLocked(sync, c, t);
699 >        assertHasExclusiveQueuedThreads(sync, NO_THREADS);
700 >        c.signal();
701 >        assertHasWaitersLocked(sync, c, NO_THREADS);
702 >        assertHasExclusiveQueuedThreads(sync, t);
703 >        sync.release();
704 >        awaitTermination(t);
705      }
706  
523
524
707      /**
708 <     * hasWaiters throws NPE if null
708 >     * hasWaiters(null) throws NullPointerException
709       */
710      public void testHasWaitersNPE() {
711 <        final Mutex lock = new Mutex();
711 >        final Mutex sync = new Mutex();
712          try {
713 <            lock.hasWaiters(null);
713 >            sync.hasWaiters(null);
714              shouldThrow();
715 <        } catch (NullPointerException success) {
534 <        } catch (Exception ex) {
535 <            unexpectedException();
536 <        }
715 >        } catch (NullPointerException success) {}
716      }
717  
718      /**
719 <     * getWaitQueueLength throws NPE if null
719 >     * getWaitQueueLength(null) throws NullPointerException
720       */
721      public void testGetWaitQueueLengthNPE() {
722 <        final Mutex lock = new Mutex();
722 >        final Mutex sync = new Mutex();
723          try {
724 <            lock.getWaitQueueLength(null);
724 >            sync.getWaitQueueLength(null);
725              shouldThrow();
726 <        } catch (NullPointerException success) {
548 <        } catch (Exception ex) {
549 <            unexpectedException();
550 <        }
726 >        } catch (NullPointerException success) {}
727      }
728  
553
729      /**
730 <     * getWaitingThreads throws NPE if null
730 >     * getWaitingThreads(null) throws NullPointerException
731       */
732      public void testGetWaitingThreadsNPE() {
733 <        final Mutex lock = new Mutex();
733 >        final Mutex sync = new Mutex();
734          try {
735 <            lock.getWaitingThreads(null);
735 >            sync.getWaitingThreads(null);
736              shouldThrow();
737 <        } catch (NullPointerException success) {
563 <        } catch (Exception ex) {
564 <            unexpectedException();
565 <        }
737 >        } catch (NullPointerException success) {}
738      }
739  
568
740      /**
741 <     * hasWaiters throws IAE if not owned
741 >     * hasWaiters throws IllegalArgumentException if not owned
742       */
743      public void testHasWaitersIAE() {
744 <        final Mutex lock = new Mutex();
745 <        final AbstractQueuedSynchronizer.ConditionObject c = (lock.newCondition());
746 <        final Mutex lock2 = new Mutex();
744 >        final Mutex sync = new Mutex();
745 >        final ConditionObject c = sync.newCondition();
746 >        final Mutex sync2 = new Mutex();
747          try {
748 <            lock2.hasWaiters(c);
748 >            sync2.hasWaiters(c);
749              shouldThrow();
750 <        } catch (IllegalArgumentException success) {
751 <        } catch (Exception ex) {
581 <            unexpectedException();
582 <        }
750 >        } catch (IllegalArgumentException success) {}
751 >        assertHasWaitersUnlocked(sync, c, NO_THREADS);
752      }
753  
754      /**
755 <     * hasWaiters throws IMSE if not locked
755 >     * hasWaiters throws IllegalMonitorStateException if not synced
756       */
757      public void testHasWaitersIMSE() {
758 <        final Mutex lock = new Mutex();
759 <        final AbstractQueuedSynchronizer.ConditionObject c = (lock.newCondition());
758 >        final Mutex sync = new Mutex();
759 >        final ConditionObject c = sync.newCondition();
760          try {
761 <            lock.hasWaiters(c);
761 >            sync.hasWaiters(c);
762              shouldThrow();
763 <        } catch (IllegalMonitorStateException success) {
764 <        } catch (Exception ex) {
596 <            unexpectedException();
597 <        }
763 >        } catch (IllegalMonitorStateException success) {}
764 >        assertHasWaitersUnlocked(sync, c, NO_THREADS);
765      }
766  
600
767      /**
768 <     * getWaitQueueLength throws IAE if not owned
768 >     * getWaitQueueLength throws IllegalArgumentException if not owned
769       */
770      public void testGetWaitQueueLengthIAE() {
771 <        final Mutex lock = new Mutex();
772 <        final AbstractQueuedSynchronizer.ConditionObject c = (lock.newCondition());
773 <        final Mutex lock2 = new Mutex();
771 >        final Mutex sync = new Mutex();
772 >        final ConditionObject c = sync.newCondition();
773 >        final Mutex sync2 = new Mutex();
774          try {
775 <            lock2.getWaitQueueLength(c);
775 >            sync2.getWaitQueueLength(c);
776              shouldThrow();
777 <        } catch (IllegalArgumentException success) {
778 <        } catch (Exception ex) {
613 <            unexpectedException();
614 <        }
777 >        } catch (IllegalArgumentException success) {}
778 >        assertHasWaitersUnlocked(sync, c, NO_THREADS);
779      }
780  
781      /**
782 <     * getWaitQueueLength throws IMSE if not locked
782 >     * getWaitQueueLength throws IllegalMonitorStateException if not synced
783       */
784      public void testGetWaitQueueLengthIMSE() {
785 <        final Mutex lock = new Mutex();
786 <        final AbstractQueuedSynchronizer.ConditionObject c = (lock.newCondition());
785 >        final Mutex sync = new Mutex();
786 >        final ConditionObject c = sync.newCondition();
787          try {
788 <            lock.getWaitQueueLength(c);
788 >            sync.getWaitQueueLength(c);
789              shouldThrow();
790 <        } catch (IllegalMonitorStateException success) {
791 <        } catch (Exception ex) {
628 <            unexpectedException();
629 <        }
790 >        } catch (IllegalMonitorStateException success) {}
791 >        assertHasWaitersUnlocked(sync, c, NO_THREADS);
792      }
793  
632
794      /**
795 <     * getWaitingThreads throws IAE if not owned
795 >     * getWaitingThreads throws IllegalArgumentException if not owned
796       */
797      public void testGetWaitingThreadsIAE() {
798 <        final Mutex lock = new Mutex();
799 <        final AbstractQueuedSynchronizer.ConditionObject c = (lock.newCondition());
800 <        final Mutex lock2 = new Mutex();        
798 >        final Mutex sync = new Mutex();
799 >        final ConditionObject c = sync.newCondition();
800 >        final Mutex sync2 = new Mutex();
801          try {
802 <            lock2.getWaitingThreads(c);
802 >            sync2.getWaitingThreads(c);
803              shouldThrow();
804 <        } catch (IllegalArgumentException success) {
805 <        } catch (Exception ex) {
645 <            unexpectedException();
646 <        }
804 >        } catch (IllegalArgumentException success) {}
805 >        assertHasWaitersUnlocked(sync, c, NO_THREADS);
806      }
807  
808      /**
809 <     * getWaitingThreads throws IMSE if not locked
809 >     * getWaitingThreads throws IllegalMonitorStateException if not synced
810       */
811      public void testGetWaitingThreadsIMSE() {
812 <        final Mutex lock = new Mutex();
813 <        final AbstractQueuedSynchronizer.ConditionObject c = (lock.newCondition());
812 >        final Mutex sync = new Mutex();
813 >        final ConditionObject c = sync.newCondition();
814          try {
815 <            lock.getWaitingThreads(c);
815 >            sync.getWaitingThreads(c);
816              shouldThrow();
817 <        } catch (IllegalMonitorStateException success) {
818 <        } catch (Exception ex) {
660 <            unexpectedException();
661 <        }
817 >        } catch (IllegalMonitorStateException success) {}
818 >        assertHasWaitersUnlocked(sync, c, NO_THREADS);
819      }
820  
664
665
821      /**
822       * hasWaiters returns true when a thread is waiting, else false
823       */
824      public void testHasWaiters() {
825 <        final Mutex lock = new Mutex();
826 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
827 <        Thread t = new Thread(new Runnable() {
828 <                public void run() {
829 <                    try {
830 <                        lock.acquireExclusiveUninterruptibly(1);
831 <                        threadAssertFalse(lock.hasWaiters(c));
832 <                        threadAssertEquals(0, lock.getWaitQueueLength(c));
833 <                        c.await();
834 <                        lock.releaseExclusive(1);
835 <                    }
836 <                    catch(InterruptedException e) {
837 <                        threadUnexpectedException();
838 <                    }
839 <                }
840 <            });
825 >        final Mutex sync = new Mutex();
826 >        final ConditionObject c = sync.newCondition();
827 >        final BooleanLatch acquired = new BooleanLatch();
828 >        Thread t = newStartedThread(new CheckedRunnable() {
829 >            public void realRun() throws InterruptedException {
830 >                sync.acquire();
831 >                assertHasWaitersLocked(sync, c, NO_THREADS);
832 >                assertFalse(sync.hasWaiters(c));
833 >                assertTrue(acquired.releaseShared(0));
834 >                c.await();
835 >                sync.release();
836 >            }});
837 >
838 >        acquired.acquireShared(0);
839 >        sync.acquire();
840 >        assertHasWaitersLocked(sync, c, t);
841 >        assertHasExclusiveQueuedThreads(sync, NO_THREADS);
842 >        assertTrue(sync.hasWaiters(c));
843 >        c.signal();
844 >        assertHasWaitersLocked(sync, c, NO_THREADS);
845 >        assertHasExclusiveQueuedThreads(sync, t);
846 >        assertFalse(sync.hasWaiters(c));
847 >        sync.release();
848  
849 <        try {
850 <            t.start();
689 <            Thread.sleep(SHORT_DELAY_MS);
690 <            lock.acquireExclusiveUninterruptibly(1);
691 <            assertTrue(lock.hasWaiters(c));
692 <            assertEquals(1, lock.getWaitQueueLength(c));
693 <            c.signal();
694 <            lock.releaseExclusive(1);
695 <            Thread.sleep(SHORT_DELAY_MS);
696 <            lock.acquireExclusiveUninterruptibly(1);
697 <            assertFalse(lock.hasWaiters(c));
698 <            assertEquals(0, lock.getWaitQueueLength(c));
699 <            lock.releaseExclusive(1);
700 <            t.join(SHORT_DELAY_MS);
701 <            assertFalse(t.isAlive());
702 <        }
703 <        catch (Exception ex) {
704 <            unexpectedException();
705 <        }
849 >        awaitTermination(t);
850 >        assertHasWaitersUnlocked(sync, c, NO_THREADS);
851      }
852  
853      /**
854       * getWaitQueueLength returns number of waiting threads
855       */
856      public void testGetWaitQueueLength() {
857 <        final Mutex lock = new Mutex();
858 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
859 <        Thread t1 = new Thread(new Runnable() {
860 <                public void run() {
861 <                    try {
862 <                        lock.acquireExclusiveUninterruptibly(1);
863 <                        threadAssertFalse(lock.hasWaiters(c));
864 <                        threadAssertEquals(0, lock.getWaitQueueLength(c));
865 <                        c.await();
866 <                        lock.releaseExclusive(1);
867 <                    }
868 <                    catch(InterruptedException e) {
869 <                        threadUnexpectedException();
870 <                    }
871 <                }
872 <            });
873 <
874 <        Thread t2 = new Thread(new Runnable() {
875 <                public void run() {
876 <                    try {
877 <                        lock.acquireExclusiveUninterruptibly(1);
878 <                        threadAssertTrue(lock.hasWaiters(c));
879 <                        threadAssertEquals(1, lock.getWaitQueueLength(c));
880 <                        c.await();
881 <                        lock.releaseExclusive(1);
882 <                    }
883 <                    catch(InterruptedException e) {
884 <                        threadUnexpectedException();
885 <                    }
886 <                }
887 <            });
888 <
889 <        try {
890 <            t1.start();
891 <            Thread.sleep(SHORT_DELAY_MS);
892 <            t2.start();
893 <            Thread.sleep(SHORT_DELAY_MS);
894 <            lock.acquireExclusiveUninterruptibly(1);
895 <            assertTrue(lock.hasWaiters(c));
896 <            assertEquals(2, lock.getWaitQueueLength(c));
897 <            c.signalAll();
898 <            lock.releaseExclusive(1);
754 <            Thread.sleep(SHORT_DELAY_MS);
755 <            lock.acquireExclusiveUninterruptibly(1);
756 <            assertFalse(lock.hasWaiters(c));
757 <            assertEquals(0, lock.getWaitQueueLength(c));
758 <            lock.releaseExclusive(1);
759 <            t1.join(SHORT_DELAY_MS);
760 <            t2.join(SHORT_DELAY_MS);
761 <            assertFalse(t1.isAlive());
762 <            assertFalse(t2.isAlive());
763 <        }
764 <        catch (Exception ex) {
765 <            unexpectedException();
766 <        }
857 >        final Mutex sync = new Mutex();
858 >        final ConditionObject c = sync.newCondition();
859 >        final BooleanLatch acquired1 = new BooleanLatch();
860 >        final BooleanLatch acquired2 = new BooleanLatch();
861 >        final Thread t1 = newStartedThread(new CheckedRunnable() {
862 >            public void realRun() throws InterruptedException {
863 >                sync.acquire();
864 >                assertHasWaitersLocked(sync, c, NO_THREADS);
865 >                assertEquals(0, sync.getWaitQueueLength(c));
866 >                assertTrue(acquired1.releaseShared(0));
867 >                c.await();
868 >                sync.release();
869 >            }});
870 >        acquired1.acquireShared(0);
871 >        sync.acquire();
872 >        assertHasWaitersLocked(sync, c, t1);
873 >        assertEquals(1, sync.getWaitQueueLength(c));
874 >        sync.release();
875 >
876 >        final Thread t2 = newStartedThread(new CheckedRunnable() {
877 >            public void realRun() throws InterruptedException {
878 >                sync.acquire();
879 >                assertHasWaitersLocked(sync, c, t1);
880 >                assertEquals(1, sync.getWaitQueueLength(c));
881 >                assertTrue(acquired2.releaseShared(0));
882 >                c.await();
883 >                sync.release();
884 >            }});
885 >        acquired2.acquireShared(0);
886 >        sync.acquire();
887 >        assertHasWaitersLocked(sync, c, t1, t2);
888 >        assertHasExclusiveQueuedThreads(sync, NO_THREADS);
889 >        assertEquals(2, sync.getWaitQueueLength(c));
890 >        c.signalAll();
891 >        assertHasWaitersLocked(sync, c, NO_THREADS);
892 >        assertHasExclusiveQueuedThreads(sync, t1, t2);
893 >        assertEquals(0, sync.getWaitQueueLength(c));
894 >        sync.release();
895 >
896 >        awaitTermination(t1);
897 >        awaitTermination(t2);
898 >        assertHasWaitersUnlocked(sync, c, NO_THREADS);
899      }
900  
901      /**
902       * getWaitingThreads returns only and all waiting threads
903       */
904      public void testGetWaitingThreads() {
905 <        final Mutex lock = new Mutex();
906 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
907 <        Thread t1 = new Thread(new Runnable() {
908 <                public void run() {
909 <                    try {
910 <                        lock.acquireExclusiveUninterruptibly(1);
911 <                        threadAssertTrue(lock.getWaitingThreads(c).isEmpty());
912 <                        c.await();
913 <                        lock.releaseExclusive(1);
914 <                    }
915 <                    catch(InterruptedException e) {
916 <                        threadUnexpectedException();
917 <                    }
918 <                }
919 <            });
920 <
921 <        Thread t2 = new Thread(new Runnable() {
922 <                public void run() {
923 <                    try {
924 <                        lock.acquireExclusiveUninterruptibly(1);
925 <                        threadAssertFalse(lock.getWaitingThreads(c).isEmpty());
926 <                        c.await();
927 <                        lock.releaseExclusive(1);
928 <                    }
929 <                    catch(InterruptedException e) {
930 <                        threadUnexpectedException();
931 <                    }
932 <                }
933 <            });
934 <
935 <        try {
936 <            lock.acquireExclusiveUninterruptibly(1);
937 <            assertTrue(lock.getWaitingThreads(c).isEmpty());
938 <            lock.releaseExclusive(1);
939 <            t1.start();
940 <            Thread.sleep(SHORT_DELAY_MS);
941 <            t2.start();
942 <            Thread.sleep(SHORT_DELAY_MS);
943 <            lock.acquireExclusiveUninterruptibly(1);
944 <            assertTrue(lock.hasWaiters(c));
945 <            assertTrue(lock.getWaitingThreads(c).contains(t1));
946 <            assertTrue(lock.getWaitingThreads(c).contains(t2));
947 <            c.signalAll();
948 <            lock.releaseExclusive(1);
949 <            Thread.sleep(SHORT_DELAY_MS);
950 <            lock.acquireExclusiveUninterruptibly(1);
951 <            assertFalse(lock.hasWaiters(c));
952 <            assertTrue(lock.getWaitingThreads(c).isEmpty());
953 <            lock.releaseExclusive(1);
954 <            t1.join(SHORT_DELAY_MS);
955 <            t2.join(SHORT_DELAY_MS);
956 <            assertFalse(t1.isAlive());
957 <            assertFalse(t2.isAlive());
958 <        }
959 <        catch (Exception ex) {
960 <            unexpectedException();
961 <        }
905 >        final Mutex sync = new Mutex();
906 >        final ConditionObject c = sync.newCondition();
907 >        final BooleanLatch acquired1 = new BooleanLatch();
908 >        final BooleanLatch acquired2 = new BooleanLatch();
909 >        final Thread t1 = new Thread(new CheckedRunnable() {
910 >            public void realRun() throws InterruptedException {
911 >                sync.acquire();
912 >                assertHasWaitersLocked(sync, c, NO_THREADS);
913 >                assertTrue(sync.getWaitingThreads(c).isEmpty());
914 >                assertTrue(acquired1.releaseShared(0));
915 >                c.await();
916 >                sync.release();
917 >            }});
918 >
919 >        final Thread t2 = new Thread(new CheckedRunnable() {
920 >            public void realRun() throws InterruptedException {
921 >                sync.acquire();
922 >                assertHasWaitersLocked(sync, c, t1);
923 >                assertTrue(sync.getWaitingThreads(c).contains(t1));
924 >                assertFalse(sync.getWaitingThreads(c).isEmpty());
925 >                assertEquals(1, sync.getWaitingThreads(c).size());
926 >                assertTrue(acquired2.releaseShared(0));
927 >                c.await();
928 >                sync.release();
929 >            }});
930 >
931 >        sync.acquire();
932 >        assertHasWaitersLocked(sync, c, NO_THREADS);
933 >        assertFalse(sync.getWaitingThreads(c).contains(t1));
934 >        assertFalse(sync.getWaitingThreads(c).contains(t2));
935 >        assertTrue(sync.getWaitingThreads(c).isEmpty());
936 >        assertEquals(0, sync.getWaitingThreads(c).size());
937 >        sync.release();
938 >
939 >        t1.start();
940 >        acquired1.acquireShared(0);
941 >        sync.acquire();
942 >        assertHasWaitersLocked(sync, c, t1);
943 >        assertTrue(sync.getWaitingThreads(c).contains(t1));
944 >        assertFalse(sync.getWaitingThreads(c).contains(t2));
945 >        assertFalse(sync.getWaitingThreads(c).isEmpty());
946 >        assertEquals(1, sync.getWaitingThreads(c).size());
947 >        sync.release();
948 >
949 >        t2.start();
950 >        acquired2.acquireShared(0);
951 >        sync.acquire();
952 >        assertHasWaitersLocked(sync, c, t1, t2);
953 >        assertHasExclusiveQueuedThreads(sync, NO_THREADS);
954 >        assertTrue(sync.getWaitingThreads(c).contains(t1));
955 >        assertTrue(sync.getWaitingThreads(c).contains(t2));
956 >        assertFalse(sync.getWaitingThreads(c).isEmpty());
957 >        assertEquals(2, sync.getWaitingThreads(c).size());
958 >        c.signalAll();
959 >        assertHasWaitersLocked(sync, c, NO_THREADS);
960 >        assertHasExclusiveQueuedThreads(sync, t1, t2);
961 >        assertFalse(sync.getWaitingThreads(c).contains(t1));
962 >        assertFalse(sync.getWaitingThreads(c).contains(t2));
963 >        assertTrue(sync.getWaitingThreads(c).isEmpty());
964 >        assertEquals(0, sync.getWaitingThreads(c).size());
965 >        sync.release();
966 >
967 >        awaitTermination(t1);
968 >        awaitTermination(t2);
969 >        assertHasWaitersUnlocked(sync, c, NO_THREADS);
970      }
971  
832
833
972      /**
973 <     * awaitUninterruptibly doesn't abort on interrupt
973 >     * awaitUninterruptibly is uninterruptible
974       */
975      public void testAwaitUninterruptibly() {
976 <        final Mutex lock = new Mutex();
977 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
978 <        Thread t = new Thread(new Runnable() {
979 <                public void run() {
980 <                    lock.acquireExclusiveUninterruptibly(1);
981 <                    c.awaitUninterruptibly();
982 <                    lock.releaseExclusive(1);
983 <                }
984 <            });
985 <
986 <        try {
987 <            t.start();
988 <            Thread.sleep(SHORT_DELAY_MS);
989 <            t.interrupt();
990 <            lock.acquireExclusiveUninterruptibly(1);
991 <            c.signal();
992 <            lock.releaseExclusive(1);
993 <            assert(t.isInterrupted());
994 <            t.join(SHORT_DELAY_MS);
995 <            assertFalse(t.isAlive());
996 <        }
997 <        catch (Exception ex) {
998 <            unexpectedException();
999 <        }
976 >        final Mutex sync = new Mutex();
977 >        final ConditionObject condition = sync.newCondition();
978 >        final BooleanLatch pleaseInterrupt = new BooleanLatch();
979 >        Thread t = newStartedThread(new CheckedRunnable() {
980 >            public void realRun() {
981 >                sync.acquire();
982 >                assertTrue(pleaseInterrupt.releaseShared(0));
983 >                condition.awaitUninterruptibly();
984 >                assertTrue(Thread.interrupted());
985 >                assertHasWaitersLocked(sync, condition, NO_THREADS);
986 >                sync.release();
987 >            }});
988 >
989 >        pleaseInterrupt.acquireShared(0);
990 >        sync.acquire();
991 >        assertHasWaitersLocked(sync, condition, t);
992 >        sync.release();
993 >        t.interrupt();
994 >        assertHasWaitersUnlocked(sync, condition, t);
995 >        assertThreadBlocks(t, Thread.State.WAITING);
996 >        sync.acquire();
997 >        assertHasWaitersLocked(sync, condition, t);
998 >        assertHasExclusiveQueuedThreads(sync, NO_THREADS);
999 >        condition.signal();
1000 >        assertHasWaitersLocked(sync, condition, NO_THREADS);
1001 >        assertHasExclusiveQueuedThreads(sync, t);
1002 >        sync.release();
1003 >        awaitTermination(t);
1004      }
1005  
1006      /**
1007 <     * await is interruptible
1008 <     */
1009 <    public void testAwait_Interrupt() {
1010 <        final Mutex lock = new Mutex();
1011 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
1012 <        Thread t = new Thread(new Runnable() {
1013 <                public void run() {
1014 <                    try {
1015 <                        lock.acquireExclusiveUninterruptibly(1);
1016 <                        c.await();
1017 <                        lock.releaseExclusive(1);
1018 <                        threadShouldThrow();
1019 <                    }
1020 <                    catch(InterruptedException success) {
1021 <                    }
1022 <                }
1023 <            });
1024 <
1025 <        try {
1026 <            t.start();
885 <            Thread.sleep(SHORT_DELAY_MS);
886 <            t.interrupt();
887 <            t.join(SHORT_DELAY_MS);
888 <            assertFalse(t.isAlive());
889 <        }
890 <        catch (Exception ex) {
891 <            unexpectedException();
892 <        }
893 <    }
894 <
895 <    /**
896 <     * awaitNanos is interruptible
897 <     */
898 <    public void testAwaitNanos_Interrupt() {
899 <        final Mutex lock = new Mutex();
900 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
901 <        Thread t = new Thread(new Runnable() {
902 <                public void run() {
903 <                    try {
904 <                        lock.acquireExclusiveUninterruptibly(1);
905 <                        c.awaitNanos(1000 * 1000 * 1000); // 1 sec
906 <                        lock.releaseExclusive(1);
907 <                        threadShouldThrow();
908 <                    }
909 <                    catch(InterruptedException success) {
910 <                    }
911 <                }
912 <            });
913 <
914 <        try {
915 <            t.start();
916 <            Thread.sleep(SHORT_DELAY_MS);
917 <            t.interrupt();
918 <            t.join(SHORT_DELAY_MS);
919 <            assertFalse(t.isAlive());
920 <        }
921 <        catch (Exception ex) {
922 <            unexpectedException();
923 <        }
924 <    }
925 <
926 <    /**
927 <     * awaitUntil is interruptible
928 <     */
929 <    public void testAwaitUntil_Interrupt() {
930 <        final Mutex lock = new Mutex();
931 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
932 <        Thread t = new Thread(new Runnable() {
933 <                public void run() {
934 <                    try {
935 <                        lock.acquireExclusiveUninterruptibly(1);
936 <                        java.util.Date d = new java.util.Date();
937 <                        c.awaitUntil(new java.util.Date(d.getTime() + 10000));
938 <                        lock.releaseExclusive(1);
939 <                        threadShouldThrow();
940 <                    }
941 <                    catch(InterruptedException success) {
942 <                    }
943 <                }
944 <            });
945 <
946 <        try {
947 <            t.start();
948 <            Thread.sleep(SHORT_DELAY_MS);
949 <            t.interrupt();
950 <            t.join(SHORT_DELAY_MS);
951 <            assertFalse(t.isAlive());
952 <        }
953 <        catch (Exception ex) {
954 <            unexpectedException();
955 <        }
1007 >     * await/awaitNanos/awaitUntil is interruptible
1008 >     */
1009 >    public void testInterruptible_await()      { testInterruptible(AwaitMethod.await); }
1010 >    public void testInterruptible_awaitTimed() { testInterruptible(AwaitMethod.awaitTimed); }
1011 >    public void testInterruptible_awaitNanos() { testInterruptible(AwaitMethod.awaitNanos); }
1012 >    public void testInterruptible_awaitUntil() { testInterruptible(AwaitMethod.awaitUntil); }
1013 >    public void testInterruptible(final AwaitMethod awaitMethod) {
1014 >        final Mutex sync = new Mutex();
1015 >        final ConditionObject c = sync.newCondition();
1016 >        final BooleanLatch pleaseInterrupt = new BooleanLatch();
1017 >        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1018 >            public void realRun() throws InterruptedException {
1019 >                sync.acquire();
1020 >                assertTrue(pleaseInterrupt.releaseShared(0));
1021 >                await(c, awaitMethod);
1022 >            }});
1023 >
1024 >        pleaseInterrupt.acquireShared(0);
1025 >        t.interrupt();
1026 >        awaitTermination(t);
1027      }
1028  
1029      /**
1030       * signalAll wakes up all threads
1031       */
1032 <    public void testSignalAll() {
1033 <        final Mutex lock = new Mutex();
1034 <        final AbstractQueuedSynchronizer.ConditionObject c = lock.newCondition();
1035 <        Thread t1 = new Thread(new Runnable() {
1036 <                public void run() {
1037 <                    try {
1038 <                        lock.acquireExclusiveUninterruptibly(1);
1039 <                        c.await();
1040 <                        lock.releaseExclusive(1);
1041 <                    }
1042 <                    catch(InterruptedException e) {
1043 <                        threadUnexpectedException();
1044 <                    }
1045 <                }
1046 <            });
1047 <
1048 <        Thread t2 = new Thread(new Runnable() {
1049 <                public void run() {
1050 <                    try {
1051 <                        lock.acquireExclusiveUninterruptibly(1);
1052 <                        c.await();
1053 <                        lock.releaseExclusive(1);
1054 <                    }
1055 <                    catch(InterruptedException e) {
1056 <                        threadUnexpectedException();
1057 <                    }
1058 <                }
1059 <            });
1060 <
1061 <        try {
1062 <            t1.start();
1063 <            t2.start();
1064 <            Thread.sleep(SHORT_DELAY_MS);
1065 <            lock.acquireExclusiveUninterruptibly(1);
1066 <            c.signalAll();
1067 <            lock.releaseExclusive(1);
997 <            t1.join(SHORT_DELAY_MS);
998 <            t2.join(SHORT_DELAY_MS);
999 <            assertFalse(t1.isAlive());
1000 <            assertFalse(t2.isAlive());
1001 <        }
1002 <        catch (Exception ex) {
1003 <            unexpectedException();
1004 <        }
1032 >    public void testSignalAll_await()      { testSignalAll(AwaitMethod.await); }
1033 >    public void testSignalAll_awaitTimed() { testSignalAll(AwaitMethod.awaitTimed); }
1034 >    public void testSignalAll_awaitNanos() { testSignalAll(AwaitMethod.awaitNanos); }
1035 >    public void testSignalAll_awaitUntil() { testSignalAll(AwaitMethod.awaitUntil); }
1036 >    public void testSignalAll(final AwaitMethod awaitMethod) {
1037 >        final Mutex sync = new Mutex();
1038 >        final ConditionObject c = sync.newCondition();
1039 >        final BooleanLatch acquired1 = new BooleanLatch();
1040 >        final BooleanLatch acquired2 = new BooleanLatch();
1041 >        Thread t1 = newStartedThread(new CheckedRunnable() {
1042 >            public void realRun() throws InterruptedException {
1043 >                sync.acquire();
1044 >                acquired1.releaseShared(0);
1045 >                await(c, awaitMethod);
1046 >                sync.release();
1047 >            }});
1048 >
1049 >        Thread t2 = newStartedThread(new CheckedRunnable() {
1050 >            public void realRun() throws InterruptedException {
1051 >                sync.acquire();
1052 >                acquired2.releaseShared(0);
1053 >                await(c, awaitMethod);
1054 >                sync.release();
1055 >            }});
1056 >
1057 >        acquired1.acquireShared(0);
1058 >        acquired2.acquireShared(0);
1059 >        sync.acquire();
1060 >        assertHasWaitersLocked(sync, c, t1, t2);
1061 >        assertHasExclusiveQueuedThreads(sync, NO_THREADS);
1062 >        c.signalAll();
1063 >        assertHasWaitersLocked(sync, c, NO_THREADS);
1064 >        assertHasExclusiveQueuedThreads(sync, t1, t2);
1065 >        sync.release();
1066 >        awaitTermination(t1);
1067 >        awaitTermination(t2);
1068      }
1069  
1007
1070      /**
1071       * toString indicates current state
1072       */
1073      public void testToString() {
1074 <        Mutex lock = new Mutex();
1075 <        String us = lock.toString();
1076 <        assertTrue(us.indexOf("State = 0") >= 0);
1077 <        lock.acquireExclusiveUninterruptibly(1);
1016 <        String ls = lock.toString();
1017 <        assertTrue(ls.indexOf("State = 1") >= 0);
1074 >        Mutex sync = new Mutex();
1075 >        assertTrue(sync.toString().contains("State = " + Mutex.UNLOCKED));
1076 >        sync.acquire();
1077 >        assertTrue(sync.toString().contains("State = " + Mutex.LOCKED));
1078      }
1079  
1080      /**
1081 <     * A serialized AQS deserializes with current state
1081 >     * A serialized AQS deserializes with current state, but no queued threads
1082       */
1083      public void testSerialization() {
1084 <        Mutex l = new Mutex();
1085 <        l.acquireExclusiveUninterruptibly(1);
1086 <        assertTrue(l.isLocked());
1087 <
1088 <        try {
1089 <            ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
1090 <            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
1091 <            out.writeObject(l);
1092 <            out.close();
1093 <
1094 <            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
1095 <            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
1096 <            Mutex r = (Mutex) in.readObject();
1097 <            assertTrue(r.isLocked());
1098 <        } catch(Exception e){
1099 <            e.printStackTrace();
1100 <            unexpectedException();
1101 <        }
1084 >        Mutex sync = new Mutex();
1085 >        assertFalse(serialClone(sync).isHeldExclusively());
1086 >        sync.acquire();
1087 >        Thread t = newStartedThread(new InterruptedSyncRunnable(sync));
1088 >        waitForQueuedThread(sync, t);
1089 >        assertTrue(sync.isHeldExclusively());
1090 >
1091 >        Mutex clone = serialClone(sync);
1092 >        assertTrue(clone.isHeldExclusively());
1093 >        assertHasExclusiveQueuedThreads(sync, t);
1094 >        assertHasExclusiveQueuedThreads(clone, NO_THREADS);
1095 >        t.interrupt();
1096 >        awaitTermination(t);
1097 >        sync.release();
1098 >        assertFalse(sync.isHeldExclusively());
1099 >        assertTrue(clone.isHeldExclusively());
1100 >        assertHasExclusiveQueuedThreads(sync, NO_THREADS);
1101 >        assertHasExclusiveQueuedThreads(clone, NO_THREADS);
1102      }
1103  
1044
1104      /**
1105       * tryReleaseShared setting state changes getState
1106       */
1107      public void testGetStateWithReleaseShared() {
1108 <        final BooleanLatch l = new BooleanLatch();
1109 <        assertFalse(l.isSignalled());
1110 <        l.releaseShared(0);
1111 <        assertTrue(l.isSignalled());
1108 >        final BooleanLatch l = new BooleanLatch();
1109 >        assertFalse(l.isSignalled());
1110 >        assertTrue(l.releaseShared(0));
1111 >        assertTrue(l.isSignalled());
1112      }
1113  
1114      /**
1115 <     * release and has no effect when already signalled
1115 >     * releaseShared has no effect when already signalled
1116       */
1117      public void testReleaseShared() {
1118 <        final BooleanLatch l = new BooleanLatch();
1119 <        assertFalse(l.isSignalled());
1120 <        l.releaseShared(0);
1121 <        assertTrue(l.isSignalled());
1122 <        l.releaseShared(0);
1123 <        assertTrue(l.isSignalled());
1118 >        final BooleanLatch l = new BooleanLatch();
1119 >        assertFalse(l.isSignalled());
1120 >        assertTrue(l.releaseShared(0));
1121 >        assertTrue(l.isSignalled());
1122 >        assertTrue(l.releaseShared(0));
1123 >        assertTrue(l.isSignalled());
1124      }
1125  
1126      /**
1127       * acquireSharedInterruptibly returns after release, but not before
1128       */
1129      public void testAcquireSharedInterruptibly() {
1130 <        final BooleanLatch l = new BooleanLatch();
1130 >        final BooleanLatch l = new BooleanLatch();
1131  
1132 <        Thread t = new Thread(new Runnable() {
1133 <                public void run() {
1134 <                    try {
1135 <                        threadAssertFalse(l.isSignalled());
1136 <                        l.acquireSharedInterruptibly(0);
1137 <                        threadAssertTrue(l.isSignalled());
1138 <                    } catch(InterruptedException e){
1139 <                        threadUnexpectedException();
1140 <                    }
1141 <                }
1142 <            });
1143 <        try {
1144 <            t.start();
1145 <            assertFalse(l.isSignalled());
1146 <            Thread.sleep(SHORT_DELAY_MS);
1147 <            l.releaseShared(0);
1089 <            assertTrue(l.isSignalled());
1090 <            t.join();
1091 <        } catch (InterruptedException e){
1092 <            unexpectedException();
1093 <        }
1094 <    }
1095 <    
1096 <
1097 <    /**
1098 <     * acquireSharedTimed returns after release
1099 <     */
1100 <    public void testAsquireSharedTimed() {
1101 <        final BooleanLatch l = new BooleanLatch();
1102 <
1103 <        Thread t = new Thread(new Runnable() {
1104 <                public void run() {
1105 <                    try {
1106 <                        threadAssertFalse(l.isSignalled());
1107 <                        threadAssertTrue(l.acquireSharedNanos(0, MEDIUM_DELAY_MS* 1000 * 1000));
1108 <                        threadAssertTrue(l.isSignalled());
1109 <
1110 <                    } catch(InterruptedException e){
1111 <                        threadUnexpectedException();
1112 <                    }
1113 <                }
1114 <            });
1115 <        try {
1116 <            t.start();
1117 <            assertFalse(l.isSignalled());
1118 <            Thread.sleep(SHORT_DELAY_MS);
1119 <            l.releaseShared(0);
1120 <            assertTrue(l.isSignalled());
1121 <            t.join();
1122 <        } catch (InterruptedException e){
1123 <            unexpectedException();
1124 <        }
1132 >        Thread t = newStartedThread(new CheckedRunnable() {
1133 >            public void realRun() throws InterruptedException {
1134 >                assertFalse(l.isSignalled());
1135 >                l.acquireSharedInterruptibly(0);
1136 >                assertTrue(l.isSignalled());
1137 >                l.acquireSharedInterruptibly(0);
1138 >                assertTrue(l.isSignalled());
1139 >            }});
1140 >
1141 >        waitForQueuedThread(l, t);
1142 >        assertFalse(l.isSignalled());
1143 >        assertThreadBlocks(t, Thread.State.WAITING);
1144 >        assertHasSharedQueuedThreads(l, t);
1145 >        assertTrue(l.releaseShared(0));
1146 >        assertTrue(l.isSignalled());
1147 >        awaitTermination(t);
1148      }
1149 <    
1149 >
1150      /**
1151 <     * acquireSharedInterruptibly throws IE if interrupted before released
1151 >     * tryAcquireSharedNanos returns after release, but not before
1152       */
1153 <    public void testAcquireSharedInterruptibly_InterruptedException() {
1153 >    public void testTryAcquireSharedNanos() {
1154          final BooleanLatch l = new BooleanLatch();
1155 <        Thread t = new Thread(new Runnable() {
1156 <                public void run() {
1157 <                    try {
1158 <                        threadAssertFalse(l.isSignalled());
1159 <                        l.acquireSharedInterruptibly(0);
1160 <                        threadShouldThrow();
1161 <                    } catch(InterruptedException success){}
1162 <                }
1163 <            });
1164 <        t.start();
1165 <        try {
1166 <            assertFalse(l.isSignalled());
1167 <            t.interrupt();
1168 <            t.join();
1169 <        } catch (InterruptedException e){
1170 <            unexpectedException();
1171 <        }
1155 >
1156 >        Thread t = newStartedThread(new CheckedRunnable() {
1157 >            public void realRun() throws InterruptedException {
1158 >                assertFalse(l.isSignalled());
1159 >                long nanos = MILLISECONDS.toNanos(2 * LONG_DELAY_MS);
1160 >                assertTrue(l.tryAcquireSharedNanos(0, nanos));
1161 >                assertTrue(l.isSignalled());
1162 >                assertTrue(l.tryAcquireSharedNanos(0, nanos));
1163 >                assertTrue(l.isSignalled());
1164 >            }});
1165 >
1166 >        waitForQueuedThread(l, t);
1167 >        assertFalse(l.isSignalled());
1168 >        assertThreadBlocks(t, Thread.State.TIMED_WAITING);
1169 >        assertTrue(l.releaseShared(0));
1170 >        assertTrue(l.isSignalled());
1171 >        awaitTermination(t);
1172      }
1173  
1174      /**
1175 <     * acquireSharedTimed throws IE if interrupted before released
1175 >     * acquireSharedInterruptibly is interruptible
1176       */
1177 <    public void testAcquireSharedNanos_InterruptedException() {
1177 >    public void testAcquireSharedInterruptibly_Interruptible() {
1178          final BooleanLatch l = new BooleanLatch();
1179 <        Thread t = new Thread(new Runnable() {
1180 <                public void run() {
1181 <                    try {
1182 <                        threadAssertFalse(l.isSignalled());
1183 <                        l.acquireSharedNanos(0, SMALL_DELAY_MS* 1000 * 1000);
1184 <                        threadShouldThrow();                        
1185 <                    } catch(InterruptedException success){}
1186 <                }
1187 <            });
1188 <        t.start();
1189 <        try {
1167 <            Thread.sleep(SHORT_DELAY_MS);
1168 <            assertFalse(l.isSignalled());
1169 <            t.interrupt();
1170 <            t.join();
1171 <        } catch (InterruptedException e){
1172 <            unexpectedException();
1173 <        }
1179 >        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1180 >            public void realRun() throws InterruptedException {
1181 >                assertFalse(l.isSignalled());
1182 >                l.acquireSharedInterruptibly(0);
1183 >            }});
1184 >
1185 >        waitForQueuedThread(l, t);
1186 >        assertFalse(l.isSignalled());
1187 >        t.interrupt();
1188 >        awaitTermination(t);
1189 >        assertFalse(l.isSignalled());
1190      }
1191  
1192      /**
1193 <     * acquireSharedTimed times out if not released before timeout
1193 >     * tryAcquireSharedNanos is interruptible
1194       */
1195 <    public void testAcquireSharedNanos_Timeout() {
1195 >    public void testTryAcquireSharedNanos_Interruptible() {
1196          final BooleanLatch l = new BooleanLatch();
1197 <        Thread t = new Thread(new Runnable() {
1198 <                public void run() {
1199 <                    try {
1200 <                        threadAssertFalse(l.isSignalled());
1201 <                        threadAssertFalse(l.acquireSharedNanos(0, SMALL_DELAY_MS* 1000 * 1000));
1202 <                    } catch(InterruptedException ie){
1203 <                        threadUnexpectedException();
1204 <                    }
1197 >        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1198 >            public void realRun() throws InterruptedException {
1199 >                assertFalse(l.isSignalled());
1200 >                long nanos = MILLISECONDS.toNanos(2 * LONG_DELAY_MS);
1201 >                l.tryAcquireSharedNanos(0, nanos);
1202 >            }});
1203 >
1204 >        waitForQueuedThread(l, t);
1205 >        assertFalse(l.isSignalled());
1206 >        t.interrupt();
1207 >        awaitTermination(t);
1208 >        assertFalse(l.isSignalled());
1209 >    }
1210 >
1211 >    /**
1212 >     * tryAcquireSharedNanos times out if not released before timeout
1213 >     */
1214 >    public void testTryAcquireSharedNanos_Timeout() {
1215 >        final BooleanLatch l = new BooleanLatch();
1216 >        final BooleanLatch observedQueued = new BooleanLatch();
1217 >        Thread t = newStartedThread(new CheckedRunnable() {
1218 >            public void realRun() throws InterruptedException {
1219 >                assertFalse(l.isSignalled());
1220 >                for (long millis = timeoutMillis();
1221 >                     !observedQueued.isSignalled();
1222 >                     millis *= 2) {
1223 >                    long nanos = MILLISECONDS.toNanos(millis);
1224 >                    long startTime = System.nanoTime();
1225 >                    assertFalse(l.tryAcquireSharedNanos(0, nanos));
1226 >                    assertTrue(millisElapsedSince(startTime) >= millis);
1227                  }
1228 <            });
1229 <        t.start();
1230 <        try {
1231 <            Thread.sleep(SHORT_DELAY_MS);
1232 <            assertFalse(l.isSignalled());
1233 <            t.join();
1234 <        } catch (InterruptedException e){
1235 <            unexpectedException();
1228 >                assertFalse(l.isSignalled());
1229 >            }});
1230 >
1231 >        waitForQueuedThread(l, t);
1232 >        observedQueued.releaseShared(0);
1233 >        assertFalse(l.isSignalled());
1234 >        awaitTermination(t);
1235 >        assertFalse(l.isSignalled());
1236 >    }
1237 >
1238 >    /**
1239 >     * awaitNanos/timed await with 0 wait times out immediately
1240 >     */
1241 >    public void testAwait_Zero() throws InterruptedException {
1242 >        final Mutex sync = new Mutex();
1243 >        final ConditionObject c = sync.newCondition();
1244 >        sync.acquire();
1245 >        assertTrue(c.awaitNanos(0L) <= 0);
1246 >        assertFalse(c.await(0L, NANOSECONDS));
1247 >        sync.release();
1248 >    }
1249 >
1250 >    /**
1251 >     * awaitNanos/timed await with maximum negative wait times does not underflow
1252 >     */
1253 >    public void testAwait_NegativeInfinity() throws InterruptedException {
1254 >        final Mutex sync = new Mutex();
1255 >        final ConditionObject c = sync.newCondition();
1256 >        sync.acquire();
1257 >        assertTrue(c.awaitNanos(Long.MIN_VALUE) <= 0);
1258 >        assertFalse(c.await(Long.MIN_VALUE, NANOSECONDS));
1259 >        sync.release();
1260 >    }
1261 >
1262 >    /**
1263 >     * JDK-8191483: AbstractQueuedSynchronizer cancel/cancel race
1264 >     * ant -Djsr166.tckTestClass=AbstractQueuedSynchronizerTest -Djsr166.methodFilter=testCancelCancelRace -Djsr166.runsPerTest=100 tck
1265 >     */
1266 >    public void testCancelCancelRace() throws InterruptedException {
1267 >        class Sync extends AbstractQueuedSynchronizer {
1268 >            protected boolean tryAcquire(int acquires) {
1269 >                return !hasQueuedPredecessors() && compareAndSetState(0, 1);
1270 >            }
1271 >            protected boolean tryRelease(int releases) {
1272 >                return compareAndSetState(1, 0);
1273 >            }
1274 >        }
1275 >
1276 >        Sync s = new Sync();
1277 >        s.acquire(1);           // acquire to force other threads to enqueue
1278 >
1279 >        // try to trigger double cancel race with two background threads
1280 >        ArrayList<Thread> threads = new ArrayList<>();
1281 >        Runnable failedAcquire = () -> {
1282 >            try {
1283 >                s.acquireInterruptibly(1);
1284 >                shouldThrow();
1285 >            } catch (InterruptedException success) {}
1286 >        };
1287 >        for (int i = 0; i < 2; i++) {
1288 >            Thread thread = new Thread(failedAcquire);
1289 >            thread.start();
1290 >            threads.add(thread);
1291 >        }
1292 >        Thread.sleep(100);
1293 >        for (Thread thread : threads) thread.interrupt();
1294 >        for (Thread thread : threads) awaitTermination(thread);
1295 >
1296 >        s.release(1);
1297 >
1298 >        // no one holds lock now, we should be able to acquire
1299 >        if (!s.tryAcquire(1))
1300 >            throw new RuntimeException(
1301 >                String.format(
1302 >                    "Broken: hasQueuedPredecessors=%s hasQueuedThreads=%s queueLength=%d firstQueuedThread=%s",
1303 >                    s.hasQueuedPredecessors(),
1304 >                    s.hasQueuedThreads(),
1305 >                    s.getQueueLength(),
1306 >                    s.getFirstQueuedThread()));
1307 >    }
1308 >
1309 >    /**
1310 >     * Tests scenario for
1311 >     * JDK-8191937: Lost interrupt in AbstractQueuedSynchronizer when tryAcquire methods throw
1312 >     * ant -Djsr166.tckTestClass=AbstractQueuedSynchronizerTest -Djsr166.methodFilter=testInterruptedFailingAcquire -Djsr166.runsPerTest=10000 tck
1313 >     */
1314 >    public void testInterruptedFailingAcquire() throws Throwable {
1315 >        final RuntimeException ex = new RuntimeException();
1316 >
1317 >        // A synchronizer only offering a choice of failure modes
1318 >        class Sync extends AbstractQueuedSynchronizer {
1319 >            volatile boolean pleaseThrow;
1320 >            @Override protected boolean tryAcquire(int ignored) {
1321 >                if (pleaseThrow) throw ex;
1322 >                return false;
1323 >            }
1324 >            @Override protected int tryAcquireShared(int ignored) {
1325 >                if (pleaseThrow) throw ex;
1326 >                return -1;
1327 >            }
1328 >            @Override protected boolean tryRelease(int ignored) {
1329 >                return true;
1330 >            }
1331 >            @Override protected boolean tryReleaseShared(int ignored) {
1332 >                return true;
1333 >            }
1334 >        }
1335 >
1336 >        final Sync s = new Sync();
1337 >        final Action[] uninterruptibleAcquireMethods = {
1338 >            () -> s.acquire(1),
1339 >            () -> s.acquireShared(1),
1340 >            // TODO: test interruptible acquire methods
1341 >        };
1342 >        final Action[] releaseMethods = {
1343 >            () -> s.release(1),
1344 >            () -> s.releaseShared(1),
1345 >        };
1346 >        final Action acquireMethod
1347 >            = chooseRandomly(uninterruptibleAcquireMethods);
1348 >        final Action releaseMethod
1349 >            = chooseRandomly(releaseMethods);
1350 >
1351 >        // From os_posix.cpp:
1352 >        //
1353 >        // NOTE that since there is no "lock" around the interrupt and
1354 >        // is_interrupted operations, there is the possibility that the
1355 >        // interrupted flag (in osThread) will be "false" but that the
1356 >        // low-level events will be in the signaled state. This is
1357 >        // intentional. The effect of this is that Object.wait() and
1358 >        // LockSupport.park() will appear to have a spurious wakeup, which
1359 >        // is allowed and not harmful, and the possibility is so rare that
1360 >        // it is not worth the added complexity to add yet another lock.
1361 >        final Thread thread = newStartedThread(new CheckedRunnable() {
1362 >            public void realRun() {
1363 >                try {
1364 >                    acquireMethod.run();
1365 >                    shouldThrow();
1366 >                } catch (Throwable t) {
1367 >                    assertSame(ex, t);
1368 >                    awaitInterrupted();
1369 >                }
1370 >            }});
1371 >        for (long startTime = 0L;; ) {
1372 >            waitForThreadToEnterWaitState(thread);
1373 >            if (s.getFirstQueuedThread() == thread
1374 >                && s.hasQueuedPredecessors()
1375 >                && s.hasQueuedThreads()
1376 >                && s.getQueueLength() == 1)
1377 >                break;
1378 >            if (startTime == 0L)
1379 >                startTime = System.nanoTime();
1380 >            else if (millisElapsedSince(startTime) > LONG_DELAY_MS)
1381 >                fail("timed out waiting for AQS state: "
1382 >                     + "thread state=" + thread.getState()
1383 >                     + ", queued threads=" + s.getQueuedThreads());
1384 >            Thread.yield();
1385 >        }
1386 >
1387 >        s.pleaseThrow = true;
1388 >        // release and interrupt, in random order
1389 >        if (randomBoolean()) {
1390 >            thread.interrupt();
1391 >            releaseMethod.run();
1392 >        } else {
1393 >            releaseMethod.run();
1394 >            thread.interrupt();
1395          }
1396 +        awaitTermination(thread);
1397      }
1398  
1201    
1399   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines