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

Comparing jsr166/src/test/tck/SynchronousQueueTest.java (file contents):
Revision 1.8 by dl, Sun Feb 15 00:27:45 2004 UTC vs.
Revision 1.43 by jsr166, Wed Dec 31 16:44:02 2014 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
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 junit.framework.*;
10 < import java.util.*;
11 < import java.util.concurrent.*;
12 < import java.io.*;
10 > import java.util.Arrays;
11 > import java.util.ArrayList;
12 > import java.util.Collection;
13 > import java.util.Iterator;
14 > import java.util.NoSuchElementException;
15 > import java.util.concurrent.BlockingQueue;
16 > import java.util.concurrent.CountDownLatch;
17 > import java.util.concurrent.Executors;
18 > import java.util.concurrent.ExecutorService;
19 > import java.util.concurrent.SynchronousQueue;
20 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
21  
22   public class SynchronousQueueTest extends JSR166TestCase {
23  
24 <    public static void main(String[] args) {
25 <        junit.textui.TestRunner.run (suite());  
24 >    public static class Fair extends BlockingQueueTest {
25 >        protected BlockingQueue emptyCollection() {
26 >            return new SynchronousQueue(true);
27 >        }
28      }
29  
30 <    public static Test suite() {
31 <        return new TestSuite(SynchronousQueueTest.class);
30 >    public static class NonFair extends BlockingQueueTest {
31 >        protected BlockingQueue emptyCollection() {
32 >            return new SynchronousQueue(false);
33 >        }
34      }
35  
36 <    /**
37 <     * A SynchronousQueue is both empty and full
38 <     */
39 <    public void testEmptyFull() {
40 <        SynchronousQueue q = new SynchronousQueue();
41 <        assertTrue(q.isEmpty());
42 <        assertEquals(0, q.size());
43 <        assertEquals(0, q.remainingCapacity());
32 <        assertFalse(q.offer(zero));
36 >    public static void main(String[] args) {
37 >        junit.textui.TestRunner.run(suite());
38 >    }
39 >
40 >    public static Test suite() {
41 >        return newTestSuite(SynchronousQueueTest.class,
42 >                            new Fair().testSuite(),
43 >                            new NonFair().testSuite());
44      }
45  
46      /**
47 <     * A fair SynchronousQueue is both empty and full
47 >     * Any SynchronousQueue is both empty and full
48       */
49 <    public void testFairEmptyFull() {
50 <        SynchronousQueue q = new SynchronousQueue(true);
49 >    public void testEmptyFull()      { testEmptyFull(false); }
50 >    public void testEmptyFull_fair() { testEmptyFull(true); }
51 >    public void testEmptyFull(boolean fair) {
52 >        final SynchronousQueue q = new SynchronousQueue(fair);
53          assertTrue(q.isEmpty());
54 <        assertEquals(0, q.size());
54 >        assertEquals(0, q.size());
55          assertEquals(0, q.remainingCapacity());
56          assertFalse(q.offer(zero));
57      }
58  
59      /**
47     * offer(null) throws NPE
48     */
49    public void testOfferNull() {
50        try {
51            SynchronousQueue q = new SynchronousQueue();
52            q.offer(null);
53            shouldThrow();
54        } catch (NullPointerException success) { }  
55    }
56
57    /**
58     * add(null) throws NPE
59     */
60    public void testAddNull() {
61        try {
62            SynchronousQueue q = new SynchronousQueue();
63            q.add(null);
64            shouldThrow();
65        } catch (NullPointerException success) { }  
66    }
67
68    /**
60       * offer fails if no active taker
61       */
62 <    public void testOffer() {
63 <        SynchronousQueue q = new SynchronousQueue();
62 >    public void testOffer()      { testOffer(false); }
63 >    public void testOffer_fair() { testOffer(true); }
64 >    public void testOffer(boolean fair) {
65 >        SynchronousQueue q = new SynchronousQueue(fair);
66          assertFalse(q.offer(one));
67      }
68  
69      /**
70 <     * add throws ISE if no active taker
70 >     * add throws IllegalStateException if no active taker
71       */
72 <    public void testAdd() {
73 <        try {
74 <            SynchronousQueue q = new SynchronousQueue();
75 <            assertEquals(0, q.remainingCapacity());
76 <            q.add(one);
84 <            shouldThrow();
85 <        } catch (IllegalStateException success){
86 <        }  
87 <    }
88 <
89 <    /**
90 <     * addAll(null) throws NPE
91 <     */
92 <    public void testAddAll1() {
72 >    public void testAdd()      { testAdd(false); }
73 >    public void testAdd_fair() { testAdd(true); }
74 >    public void testAdd(boolean fair) {
75 >        SynchronousQueue q = new SynchronousQueue(fair);
76 >        assertEquals(0, q.remainingCapacity());
77          try {
78 <            SynchronousQueue q = new SynchronousQueue();
95 <            q.addAll(null);
78 >            q.add(one);
79              shouldThrow();
80 <        }
98 <        catch (NullPointerException success) {}
80 >        } catch (IllegalStateException success) {}
81      }
82  
83      /**
84 <     * addAll(this) throws IAE
84 >     * addAll(this) throws IllegalArgumentException
85       */
86 <    public void testAddAllSelf() {
86 >    public void testAddAll_self()      { testAddAll_self(false); }
87 >    public void testAddAll_self_fair() { testAddAll_self(true); }
88 >    public void testAddAll_self(boolean fair) {
89 >        SynchronousQueue q = new SynchronousQueue(fair);
90          try {
106            SynchronousQueue q = new SynchronousQueue();
91              q.addAll(q);
92              shouldThrow();
93 <        }
110 <        catch (IllegalArgumentException success) {}
93 >        } catch (IllegalArgumentException success) {}
94      }
95  
96      /**
114     * addAll of a collection with null elements throws NPE
115     */
116    public void testAddAll2() {
117        try {
118            SynchronousQueue q = new SynchronousQueue();
119            Integer[] ints = new Integer[1];
120            q.addAll(Arrays.asList(ints));
121            shouldThrow();
122        }
123        catch (NullPointerException success) {}
124    }
125    /**
97       * addAll throws ISE if no active taker
98       */
99 <    public void testAddAll4() {
99 >    public void testAddAll_ISE()      { testAddAll_ISE(false); }
100 >    public void testAddAll_ISE_fair() { testAddAll_ISE(true); }
101 >    public void testAddAll_ISE(boolean fair) {
102 >        SynchronousQueue q = new SynchronousQueue(fair);
103 >        Integer[] ints = new Integer[1];
104 >        for (int i = 0; i < ints.length; i++)
105 >            ints[i] = i;
106 >        Collection<Integer> coll = Arrays.asList(ints);
107          try {
108 <            SynchronousQueue q = new SynchronousQueue();
131 <            Integer[] ints = new Integer[1];
132 <            for (int i = 0; i < 1; ++i)
133 <                ints[i] = new Integer(i);
134 <            q.addAll(Arrays.asList(ints));
108 >            q.addAll(coll);
109              shouldThrow();
110 <        }
137 <        catch (IllegalStateException success) {}
110 >        } catch (IllegalStateException success) {}
111      }
112  
113      /**
141     * put(null) throws NPE
142     */
143    public void testPutNull() {
144        try {
145            SynchronousQueue q = new SynchronousQueue();
146            q.put(null);
147            shouldThrow();
148        }
149        catch (NullPointerException success){
150        }  
151        catch (InterruptedException ie) {
152            unexpectedException();
153        }
154     }
155
156    /**
114       * put blocks interruptibly if no active taker
115       */
116 <    public void testBlockingPut() {
117 <        Thread t = new Thread(new Runnable() {
118 <                public void run() {
119 <                    try {
120 <                        SynchronousQueue q = new SynchronousQueue();
121 <                        q.put(zero);
122 <                        threadShouldThrow();
123 <                    } catch (InterruptedException ie){
124 <                    }  
125 <                }});
126 <        t.start();
127 <        try {
128 <           Thread.sleep(SHORT_DELAY_MS);
172 <           t.interrupt();
173 <           t.join();
174 <        }
175 <        catch (InterruptedException ie) {
176 <            unexpectedException();
177 <        }
178 <    }
116 >    public void testBlockingPut()      { testBlockingPut(false); }
117 >    public void testBlockingPut_fair() { testBlockingPut(true); }
118 >    public void testBlockingPut(boolean fair) {
119 >        final SynchronousQueue q = new SynchronousQueue(fair);
120 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
121 >        Thread t = newStartedThread(new CheckedRunnable() {
122 >            public void realRun() throws InterruptedException {
123 >                Thread.currentThread().interrupt();
124 >                try {
125 >                    q.put(99);
126 >                    shouldThrow();
127 >                } catch (InterruptedException success) {}
128 >                assertFalse(Thread.interrupted());
129  
130 <    /**
131 <     * put blocks waiting for take
132 <     */
133 <    public void testPutWithTake() {
134 <        final SynchronousQueue q = new SynchronousQueue();
135 <        Thread t = new Thread(new Runnable() {
136 <                public void run() {
137 <                    int added = 0;
138 <                    try {
139 <                        q.put(new Object());
140 <                        ++added;
141 <                        q.put(new Object());
142 <                        ++added;
193 <                        q.put(new Object());
194 <                        ++added;
195 <                        q.put(new Object());
196 <                        ++added;
197 <                        threadShouldThrow();
198 <                    } catch (InterruptedException e){
199 <                        assertTrue(added >= 1);
200 <                    }
201 <                }
202 <            });
203 <        try {
204 <            t.start();
205 <            Thread.sleep(SHORT_DELAY_MS);
206 <            q.take();
207 <            Thread.sleep(SHORT_DELAY_MS);
208 <            t.interrupt();
209 <            t.join();
210 <        } catch (Exception e){
211 <            unexpectedException();
212 <        }
130 >                pleaseInterrupt.countDown();
131 >                try {
132 >                    q.put(99);
133 >                    shouldThrow();
134 >                } catch (InterruptedException success) {}
135 >                assertFalse(Thread.interrupted());
136 >            }});
137 >
138 >        await(pleaseInterrupt);
139 >        assertThreadStaysAlive(t);
140 >        t.interrupt();
141 >        awaitTermination(t);
142 >        assertEquals(0, q.remainingCapacity());
143      }
144  
145      /**
146 <     * timed offer times out if elements not taken
146 >     * put blocks interruptibly waiting for take
147       */
148 <    public void testTimedOffer() {
149 <        final SynchronousQueue q = new SynchronousQueue();
150 <        Thread t = new Thread(new Runnable() {
151 <                public void run() {
152 <                    try {
153 <
154 <                        threadAssertFalse(q.offer(new Object(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
155 <                        q.offer(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
156 <                        threadShouldThrow();
157 <                    } catch (InterruptedException success){}
228 <                }
229 <            });
230 <        
231 <        try {
232 <            t.start();
233 <            Thread.sleep(SMALL_DELAY_MS);
234 <            t.interrupt();
235 <            t.join();
236 <        } catch (Exception e){
237 <            unexpectedException();
238 <        }
239 <    }
240 <
241 <
242 <    /**
243 <     * take blocks interruptibly when empty
244 <     */
245 <    public void testTakeFromEmpty() {
246 <        final SynchronousQueue q = new SynchronousQueue();
247 <        Thread t = new Thread(new Runnable() {
248 <                public void run() {
249 <                    try {
250 <                        q.take();
251 <                        threadShouldThrow();
252 <                    } catch (InterruptedException success){ }                
253 <                }
254 <            });
255 <        try {
256 <            t.start();
257 <            Thread.sleep(SHORT_DELAY_MS);
258 <            t.interrupt();
259 <            t.join();
260 <        } catch (Exception e){
261 <            unexpectedException();
262 <        }
263 <    }
148 >    public void testPutWithTake()      { testPutWithTake(false); }
149 >    public void testPutWithTake_fair() { testPutWithTake(true); }
150 >    public void testPutWithTake(boolean fair) {
151 >        final SynchronousQueue q = new SynchronousQueue(fair);
152 >        final CountDownLatch pleaseTake = new CountDownLatch(1);
153 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
154 >        Thread t = newStartedThread(new CheckedRunnable() {
155 >            public void realRun() throws InterruptedException {
156 >                pleaseTake.countDown();
157 >                q.put(one);
158  
159 +                pleaseInterrupt.countDown();
160 +                try {
161 +                    q.put(99);
162 +                    shouldThrow();
163 +                } catch (InterruptedException success) {}
164 +                assertFalse(Thread.interrupted());
165 +            }});
166  
167 <    /**
168 <     * put blocks interruptibly if no active taker
169 <     */
170 <    public void testFairBlockingPut() {
270 <        Thread t = new Thread(new Runnable() {
271 <                public void run() {
272 <                    try {
273 <                        SynchronousQueue q = new SynchronousQueue(true);
274 <                        q.put(zero);
275 <                        threadShouldThrow();
276 <                    } catch (InterruptedException ie){
277 <                    }  
278 <                }});
279 <        t.start();
280 <        try {
281 <           Thread.sleep(SHORT_DELAY_MS);
282 <           t.interrupt();
283 <           t.join();
284 <        }
285 <        catch (InterruptedException ie) {
286 <            unexpectedException();
287 <        }
288 <    }
167 >        await(pleaseTake);
168 >        assertEquals(0, q.remainingCapacity());
169 >        try { assertSame(one, q.take()); }
170 >        catch (InterruptedException e) { threadUnexpectedException(e); }
171  
172 <    /**
173 <     * put blocks waiting for take
174 <     */
175 <    public void testFairPutWithTake() {
176 <        final SynchronousQueue q = new SynchronousQueue(true);
295 <        Thread t = new Thread(new Runnable() {
296 <                public void run() {
297 <                    int added = 0;
298 <                    try {
299 <                        q.put(new Object());
300 <                        ++added;
301 <                        q.put(new Object());
302 <                        ++added;
303 <                        q.put(new Object());
304 <                        ++added;
305 <                        q.put(new Object());
306 <                        ++added;
307 <                        threadShouldThrow();
308 <                    } catch (InterruptedException e){
309 <                        assertTrue(added >= 1);
310 <                    }
311 <                }
312 <            });
313 <        try {
314 <            t.start();
315 <            Thread.sleep(SHORT_DELAY_MS);
316 <            q.take();
317 <            Thread.sleep(SHORT_DELAY_MS);
318 <            t.interrupt();
319 <            t.join();
320 <        } catch (Exception e){
321 <            unexpectedException();
322 <        }
172 >        await(pleaseInterrupt);
173 >        assertThreadStaysAlive(t);
174 >        t.interrupt();
175 >        awaitTermination(t);
176 >        assertEquals(0, q.remainingCapacity());
177      }
178  
179      /**
180       * timed offer times out if elements not taken
181       */
182 <    public void testFairTimedOffer() {
183 <        final SynchronousQueue q = new SynchronousQueue(true);
184 <        Thread t = new Thread(new Runnable() {
185 <                public void run() {
186 <                    try {
187 <
188 <                        threadAssertFalse(q.offer(new Object(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
189 <                        q.offer(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
190 <                        threadShouldThrow();
191 <                    } catch (InterruptedException success){}
192 <                }
193 <            });
194 <        
195 <        try {
196 <            t.start();
197 <            Thread.sleep(SMALL_DELAY_MS);
344 <            t.interrupt();
345 <            t.join();
346 <        } catch (Exception e){
347 <            unexpectedException();
348 <        }
349 <    }
182 >    public void testTimedOffer()      { testTimedOffer(false); }
183 >    public void testTimedOffer_fair() { testTimedOffer(true); }
184 >    public void testTimedOffer(boolean fair) {
185 >        final SynchronousQueue q = new SynchronousQueue(fair);
186 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
187 >        Thread t = newStartedThread(new CheckedRunnable() {
188 >            public void realRun() throws InterruptedException {
189 >                long startTime = System.nanoTime();
190 >                assertFalse(q.offer(new Object(), timeoutMillis(), MILLISECONDS));
191 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
192 >                pleaseInterrupt.countDown();
193 >                try {
194 >                    q.offer(new Object(), 2 * LONG_DELAY_MS, MILLISECONDS);
195 >                    shouldThrow();
196 >                } catch (InterruptedException success) {}
197 >            }});
198  
199 +        await(pleaseInterrupt);
200 +        assertThreadStaysAlive(t);
201 +        t.interrupt();
202 +        awaitTermination(t);
203 +    }
204  
205      /**
206 <     * take blocks interruptibly when empty
206 >     * poll return null if no active putter
207       */
208 <    public void testFairTakeFromEmpty() {
209 <        final SynchronousQueue q = new SynchronousQueue(true);
210 <        Thread t = new Thread(new Runnable() {
211 <                public void run() {
212 <                    try {
360 <                        q.take();
361 <                        threadShouldThrow();
362 <                    } catch (InterruptedException success){ }                
363 <                }
364 <            });
365 <        try {
366 <            t.start();
367 <            Thread.sleep(SHORT_DELAY_MS);
368 <            t.interrupt();
369 <            t.join();
370 <        } catch (Exception e){
371 <            unexpectedException();
372 <        }
208 >    public void testPoll()      { testPoll(false); }
209 >    public void testPoll_fair() { testPoll(true); }
210 >    public void testPoll(boolean fair) {
211 >        final SynchronousQueue q = new SynchronousQueue(fair);
212 >        assertNull(q.poll());
213      }
214  
215      /**
216 <     * poll fails unless active taker
216 >     * timed poll with zero timeout times out if no active putter
217       */
218 <    public void testPoll() {
219 <        SynchronousQueue q = new SynchronousQueue();
220 <        assertNull(q.poll());
218 >    public void testTimedPoll0()      { testTimedPoll0(false); }
219 >    public void testTimedPoll0_fair() { testTimedPoll0(true); }
220 >    public void testTimedPoll0(boolean fair) {
221 >        final SynchronousQueue q = new SynchronousQueue(fair);
222 >        try { assertNull(q.poll(0, MILLISECONDS)); }
223 >        catch (InterruptedException e) { threadUnexpectedException(e); }
224      }
225  
226      /**
227 <     * timed pool with zero timeout times out if no active taker
227 >     * timed poll with nonzero timeout times out if no active putter
228       */
229 <    public void testTimedPoll0() {
230 <        try {
231 <            SynchronousQueue q = new SynchronousQueue();
232 <            assertNull(q.poll(0, TimeUnit.MILLISECONDS));
233 <        } catch (InterruptedException e){
234 <            unexpectedException();
235 <        }  
229 >    public void testTimedPoll()      { testTimedPoll(false); }
230 >    public void testTimedPoll_fair() { testTimedPoll(true); }
231 >    public void testTimedPoll(boolean fair) {
232 >        final SynchronousQueue q = new SynchronousQueue(fair);
233 >        long startTime = System.nanoTime();
234 >        try { assertNull(q.poll(timeoutMillis(), MILLISECONDS)); }
235 >        catch (InterruptedException e) { threadUnexpectedException(e); }
236 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
237      }
238  
239      /**
240 <     * timed pool with nonzero timeout times out if no active taker
240 >     * timed poll before a delayed offer times out, returning null;
241 >     * after offer succeeds; on interruption throws
242       */
243 <    public void testTimedPoll() {
244 <        try {
245 <            SynchronousQueue q = new SynchronousQueue();
246 <            assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
247 <        } catch (InterruptedException e){
248 <            unexpectedException();
249 <        }  
250 <    }
243 >    public void testTimedPollWithOffer()      { testTimedPollWithOffer(false); }
244 >    public void testTimedPollWithOffer_fair() { testTimedPollWithOffer(true); }
245 >    public void testTimedPollWithOffer(boolean fair) {
246 >        final SynchronousQueue q = new SynchronousQueue(fair);
247 >        final CountDownLatch pleaseOffer = new CountDownLatch(1);
248 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
249 >        Thread t = newStartedThread(new CheckedRunnable() {
250 >            public void realRun() throws InterruptedException {
251 >                long startTime = System.nanoTime();
252 >                assertNull(q.poll(timeoutMillis(), MILLISECONDS));
253 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
254  
255 <    /**
256 <     * Interrupted timed poll throws InterruptedException instead of
257 <     * returning timeout status
258 <     */
411 <    public void testInterruptedTimedPoll() {
412 <        Thread t = new Thread(new Runnable() {
413 <                public void run() {
414 <                    try {
415 <                        SynchronousQueue q = new SynchronousQueue();
416 <                        assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
417 <                    } catch (InterruptedException success){
418 <                    }  
419 <                }});
420 <        t.start();
421 <        try {
422 <           Thread.sleep(SHORT_DELAY_MS);
423 <           t.interrupt();
424 <           t.join();
425 <        }
426 <        catch (InterruptedException ie) {
427 <            unexpectedException();
428 <        }
429 <    }
255 >                pleaseOffer.countDown();
256 >                startTime = System.nanoTime();
257 >                assertSame(zero, q.poll(LONG_DELAY_MS, MILLISECONDS));
258 >                assertTrue(millisElapsedSince(startTime) < MEDIUM_DELAY_MS);
259  
260 <    /**
261 <     *  timed poll before a delayed offer fails; after offer succeeds;
262 <     *  on interruption throws
263 <     */
264 <    public void testTimedPollWithOffer() {
265 <        final SynchronousQueue q = new SynchronousQueue();
437 <        Thread t = new Thread(new Runnable() {
438 <                public void run() {
439 <                    try {
440 <                        threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
441 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
442 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
443 <                        threadShouldThrow();
444 <                    } catch (InterruptedException success) { }                
445 <                }
446 <            });
447 <        try {
448 <            t.start();
449 <            Thread.sleep(SMALL_DELAY_MS);
450 <            assertTrue(q.offer(zero, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
451 <            t.interrupt();
452 <            t.join();
453 <        } catch (Exception e){
454 <            unexpectedException();
455 <        }
456 <    }  
260 >                Thread.currentThread().interrupt();
261 >                try {
262 >                    q.poll(LONG_DELAY_MS, MILLISECONDS);
263 >                    shouldThrow();
264 >                } catch (InterruptedException success) {}
265 >                assertFalse(Thread.interrupted());
266  
267 <    /**
268 <     * Interrupted timed poll throws InterruptedException instead of
269 <     * returning timeout status
270 <     */
271 <    public void testFairInterruptedTimedPoll() {
272 <        Thread t = new Thread(new Runnable() {
273 <                public void run() {
465 <                    try {
466 <                        SynchronousQueue q = new SynchronousQueue(true);
467 <                        assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
468 <                    } catch (InterruptedException success){
469 <                    }  
470 <                }});
471 <        t.start();
472 <        try {
473 <           Thread.sleep(SHORT_DELAY_MS);
474 <           t.interrupt();
475 <           t.join();
476 <        }
477 <        catch (InterruptedException ie) {
478 <            unexpectedException();
479 <        }
480 <    }
267 >                pleaseInterrupt.countDown();
268 >                try {
269 >                    q.poll(LONG_DELAY_MS, MILLISECONDS);
270 >                    shouldThrow();
271 >                } catch (InterruptedException success) {}
272 >                assertFalse(Thread.interrupted());
273 >            }});
274  
275 <    /**
276 <     *  timed poll before a delayed offer fails; after offer succeeds;
277 <     *  on interruption throws
278 <     */
279 <    public void testFairTimedPollWithOffer() {
487 <        final SynchronousQueue q = new SynchronousQueue(true);
488 <        Thread t = new Thread(new Runnable() {
489 <                public void run() {
490 <                    try {
491 <                        threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
492 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
493 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
494 <                        threadShouldThrow();
495 <                    } catch (InterruptedException success) { }                
496 <                }
497 <            });
498 <        try {
499 <            t.start();
500 <            Thread.sleep(SMALL_DELAY_MS);
501 <            assertTrue(q.offer(zero, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
502 <            t.interrupt();
503 <            t.join();
504 <        } catch (Exception e){
505 <            unexpectedException();
506 <        }
507 <    }  
275 >        await(pleaseOffer);
276 >        long startTime = System.nanoTime();
277 >        try { assertTrue(q.offer(zero, LONG_DELAY_MS, MILLISECONDS)); }
278 >        catch (InterruptedException e) { threadUnexpectedException(e); }
279 >        assertTrue(millisElapsedSince(startTime) < MEDIUM_DELAY_MS);
280  
281 +        await(pleaseInterrupt);
282 +        assertThreadStaysAlive(t);
283 +        t.interrupt();
284 +        awaitTermination(t);
285 +    }
286  
287      /**
288 <     * peek returns null
288 >     * peek() returns null if no active putter
289       */
290 <    public void testPeek() {
291 <        SynchronousQueue q = new SynchronousQueue();
292 <        assertNull(q.peek());
290 >    public void testPeek()      { testPeek(false); }
291 >    public void testPeek_fair() { testPeek(true); }
292 >    public void testPeek(boolean fair) {
293 >        final SynchronousQueue q = new SynchronousQueue(fair);
294 >        assertNull(q.peek());
295      }
296  
297      /**
298 <     * element throws NSEE
298 >     * element() throws NoSuchElementException if no active putter
299       */
300 <    public void testElement() {
301 <        SynchronousQueue q = new SynchronousQueue();
300 >    public void testElement()      { testElement(false); }
301 >    public void testElement_fair() { testElement(true); }
302 >    public void testElement(boolean fair) {
303 >        final SynchronousQueue q = new SynchronousQueue(fair);
304          try {
305              q.element();
306              shouldThrow();
307 <        }
527 <        catch (NoSuchElementException success) {}
307 >        } catch (NoSuchElementException success) {}
308      }
309  
310      /**
311 <     * remove throws NSEE if no active taker
311 >     * remove() throws NoSuchElementException if no active putter
312       */
313 <    public void testRemove() {
314 <        SynchronousQueue q = new SynchronousQueue();
313 >    public void testRemove()      { testRemove(false); }
314 >    public void testRemove_fair() { testRemove(true); }
315 >    public void testRemove(boolean fair) {
316 >        final SynchronousQueue q = new SynchronousQueue(fair);
317          try {
318              q.remove();
319              shouldThrow();
320 <        } catch (NoSuchElementException success){
539 <        }  
320 >        } catch (NoSuchElementException success) {}
321      }
322  
323      /**
543     * remove(x) returns false
544     */
545    public void testRemoveElement() {
546        SynchronousQueue q = new SynchronousQueue();
547        assertFalse(q.remove(zero));
548        assertTrue(q.isEmpty());
549    }
550        
551    /**
324       * contains returns false
325       */
326 <    public void testContains() {
327 <        SynchronousQueue q = new SynchronousQueue();
326 >    public void testContains()      { testContains(false); }
327 >    public void testContains_fair() { testContains(true); }
328 >    public void testContains(boolean fair) {
329 >        final SynchronousQueue q = new SynchronousQueue(fair);
330          assertFalse(q.contains(zero));
331      }
332  
333      /**
334       * clear ensures isEmpty
335       */
336 <    public void testClear() {
337 <        SynchronousQueue q = new SynchronousQueue();
336 >    public void testClear()      { testClear(false); }
337 >    public void testClear_fair() { testClear(true); }
338 >    public void testClear(boolean fair) {
339 >        final SynchronousQueue q = new SynchronousQueue(fair);
340          q.clear();
341          assertTrue(q.isEmpty());
342      }
# Line 568 | Line 344 | public class SynchronousQueueTest extend
344      /**
345       * containsAll returns false unless empty
346       */
347 <    public void testContainsAll() {
348 <        SynchronousQueue q = new SynchronousQueue();
347 >    public void testContainsAll()      { testContainsAll(false); }
348 >    public void testContainsAll_fair() { testContainsAll(true); }
349 >    public void testContainsAll(boolean fair) {
350 >        final SynchronousQueue q = new SynchronousQueue(fair);
351          Integer[] empty = new Integer[0];
352          assertTrue(q.containsAll(Arrays.asList(empty)));
353          Integer[] ints = new Integer[1]; ints[0] = zero;
# Line 579 | Line 357 | public class SynchronousQueueTest extend
357      /**
358       * retainAll returns false
359       */
360 <    public void testRetainAll() {
361 <        SynchronousQueue q = new SynchronousQueue();
360 >    public void testRetainAll()      { testRetainAll(false); }
361 >    public void testRetainAll_fair() { testRetainAll(true); }
362 >    public void testRetainAll(boolean fair) {
363 >        final SynchronousQueue q = new SynchronousQueue(fair);
364          Integer[] empty = new Integer[0];
365          assertFalse(q.retainAll(Arrays.asList(empty)));
366          Integer[] ints = new Integer[1]; ints[0] = zero;
# Line 590 | Line 370 | public class SynchronousQueueTest extend
370      /**
371       * removeAll returns false
372       */
373 <    public void testRemoveAll() {
374 <        SynchronousQueue q = new SynchronousQueue();
373 >    public void testRemoveAll()      { testRemoveAll(false); }
374 >    public void testRemoveAll_fair() { testRemoveAll(true); }
375 >    public void testRemoveAll(boolean fair) {
376 >        final SynchronousQueue q = new SynchronousQueue(fair);
377          Integer[] empty = new Integer[0];
378          assertFalse(q.removeAll(Arrays.asList(empty)));
379          Integer[] ints = new Integer[1]; ints[0] = zero;
380          assertFalse(q.containsAll(Arrays.asList(ints)));
381      }
382  
601
383      /**
384       * toArray is empty
385       */
386 <    public void testToArray() {
387 <        SynchronousQueue q = new SynchronousQueue();
388 <        Object[] o = q.toArray();
389 <        assertEquals(o.length, 0);
386 >    public void testToArray()      { testToArray(false); }
387 >    public void testToArray_fair() { testToArray(true); }
388 >    public void testToArray(boolean fair) {
389 >        final SynchronousQueue q = new SynchronousQueue(fair);
390 >        Object[] o = q.toArray();
391 >        assertEquals(0, o.length);
392      }
393  
394      /**
395 <     * toArray(a) is nulled at position 0
396 <     */
397 <    public void testToArray2() {
398 <        SynchronousQueue q = new SynchronousQueue();
399 <        Integer[] ints = new Integer[1];
400 <        assertNull(ints[0]);
395 >     * toArray(Integer array) returns its argument with the first
396 >     * element (if present) nulled out
397 >     */
398 >    public void testToArray2()      { testToArray2(false); }
399 >    public void testToArray2_fair() { testToArray2(true); }
400 >    public void testToArray2(boolean fair) {
401 >        final SynchronousQueue<Integer> q
402 >            = new SynchronousQueue<Integer>(fair);
403 >        Integer[] a;
404 >
405 >        a = new Integer[0];
406 >        assertSame(a, q.toArray(a));
407 >
408 >        a = new Integer[3];
409 >        Arrays.fill(a, 42);
410 >        assertSame(a, q.toArray(a));
411 >        assertNull(a[0]);
412 >        for (int i = 1; i < a.length; i++)
413 >            assertEquals(42, (int) a[i]);
414      }
415 <    
415 >
416      /**
417       * toArray(null) throws NPE
418       */
419 <    public void testToArray_BadArg() {
420 <        try {
421 <            SynchronousQueue q = new SynchronousQueue();
422 <            Object o[] = q.toArray(null);
423 <            shouldThrow();
424 <        } catch(NullPointerException success){}
419 >    public void testToArray_null()      { testToArray_null(false); }
420 >    public void testToArray_null_fair() { testToArray_null(true); }
421 >    public void testToArray_null(boolean fair) {
422 >        final SynchronousQueue q = new SynchronousQueue(fair);
423 >        try {
424 >            Object o[] = q.toArray(null);
425 >            shouldThrow();
426 >        } catch (NullPointerException success) {}
427      }
428  
631
429      /**
430       * iterator does not traverse any elements
431       */
432 <    public void testIterator() {
433 <        SynchronousQueue q = new SynchronousQueue();
434 <        Iterator it = q.iterator();
432 >    public void testIterator()      { testIterator(false); }
433 >    public void testIterator_fair() { testIterator(true); }
434 >    public void testIterator(boolean fair) {
435 >        final SynchronousQueue q = new SynchronousQueue(fair);
436 >        Iterator it = q.iterator();
437          assertFalse(it.hasNext());
438          try {
439              Object x = it.next();
440              shouldThrow();
441 <        }
643 <        catch (NoSuchElementException success) {}
441 >        } catch (NoSuchElementException success) {}
442      }
443  
444      /**
445       * iterator remove throws ISE
446       */
447 <    public void testIteratorRemove() {
448 <        SynchronousQueue q = new SynchronousQueue();
449 <        Iterator it = q.iterator();
447 >    public void testIteratorRemove()      { testIteratorRemove(false); }
448 >    public void testIteratorRemove_fair() { testIteratorRemove(true); }
449 >    public void testIteratorRemove(boolean fair) {
450 >        final SynchronousQueue q = new SynchronousQueue(fair);
451 >        Iterator it = q.iterator();
452          try {
453              it.remove();
454              shouldThrow();
455 <        }
656 <        catch (IllegalStateException success) {}
455 >        } catch (IllegalStateException success) {}
456      }
457  
458      /**
459       * toString returns a non-null string
460       */
461 <    public void testToString() {
462 <        SynchronousQueue q = new SynchronousQueue();
461 >    public void testToString()      { testToString(false); }
462 >    public void testToString_fair() { testToString(true); }
463 >    public void testToString(boolean fair) {
464 >        final SynchronousQueue q = new SynchronousQueue(fair);
465          String s = q.toString();
466          assertNotNull(s);
467 <    }        
667 <
467 >    }
468  
469      /**
470       * offer transfers elements across Executor tasks
471       */
472 <    public void testOfferInExecutor() {
473 <        final SynchronousQueue q = new SynchronousQueue();
472 >    public void testOfferInExecutor()      { testOfferInExecutor(false); }
473 >    public void testOfferInExecutor_fair() { testOfferInExecutor(true); }
474 >    public void testOfferInExecutor(boolean fair) {
475 >        final SynchronousQueue q = new SynchronousQueue(fair);
476          ExecutorService executor = Executors.newFixedThreadPool(2);
477 <        final Integer one = new Integer(1);
477 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
478  
479 <        executor.execute(new Runnable() {
480 <            public void run() {
481 <                threadAssertFalse(q.offer(one));
482 <                try {
483 <                    threadAssertTrue(q.offer(one, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
484 <                    threadAssertEquals(0, q.remainingCapacity());
485 <                }
486 <                catch (InterruptedException e) {
487 <                    threadUnexpectedException();
488 <                }
489 <            }
490 <        });
479 >        executor.execute(new CheckedRunnable() {
480 >            public void realRun() throws InterruptedException {
481 >                assertFalse(q.offer(one));
482 >                threadsStarted.await();
483 >                assertTrue(q.offer(one, LONG_DELAY_MS, MILLISECONDS));
484 >                assertEquals(0, q.remainingCapacity());
485 >            }});
486 >
487 >        executor.execute(new CheckedRunnable() {
488 >            public void realRun() throws InterruptedException {
489 >                threadsStarted.await();
490 >                assertSame(one, q.take());
491 >            }});
492  
690        executor.execute(new Runnable() {
691            public void run() {
692                try {
693                    Thread.sleep(SMALL_DELAY_MS);
694                    threadAssertEquals(one, q.take());
695                }
696                catch (InterruptedException e) {
697                    threadUnexpectedException();
698                }
699            }
700        });
701        
493          joinPool(executor);
703
494      }
495  
496      /**
497 <     * poll retrieves elements across Executor threads
497 >     * timed poll retrieves elements across Executor threads
498       */
499 <    public void testPollInExecutor() {
500 <        final SynchronousQueue q = new SynchronousQueue();
499 >    public void testPollInExecutor()      { testPollInExecutor(false); }
500 >    public void testPollInExecutor_fair() { testPollInExecutor(true); }
501 >    public void testPollInExecutor(boolean fair) {
502 >        final SynchronousQueue q = new SynchronousQueue(fair);
503 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
504          ExecutorService executor = Executors.newFixedThreadPool(2);
505 <        executor.execute(new Runnable() {
506 <            public void run() {
507 <                threadAssertNull(q.poll());
508 <                try {
509 <                    threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
510 <                    threadAssertTrue(q.isEmpty());
511 <                }
512 <                catch (InterruptedException e) {
513 <                    threadUnexpectedException();
514 <                }
515 <            }
516 <        });
505 >        executor.execute(new CheckedRunnable() {
506 >            public void realRun() throws InterruptedException {
507 >                assertNull(q.poll());
508 >                threadsStarted.await();
509 >                assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
510 >                assertTrue(q.isEmpty());
511 >            }});
512 >
513 >        executor.execute(new CheckedRunnable() {
514 >            public void realRun() throws InterruptedException {
515 >                threadsStarted.await();
516 >                q.put(one);
517 >            }});
518  
725        executor.execute(new Runnable() {
726            public void run() {
727                try {
728                    Thread.sleep(SMALL_DELAY_MS);
729                    q.put(new Integer(1));
730                }
731                catch (InterruptedException e) {
732                    threadUnexpectedException();
733                }
734            }
735        });
736        
519          joinPool(executor);
520      }
521  
# Line 741 | Line 523 | public class SynchronousQueueTest extend
523       * a deserialized serialized queue is usable
524       */
525      public void testSerialization() {
526 <        SynchronousQueue q = new SynchronousQueue();
527 <        try {
528 <            ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
529 <            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
530 <            out.writeObject(q);
531 <            out.close();
532 <
533 <            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
534 <            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
535 <            SynchronousQueue r = (SynchronousQueue)in.readObject();
536 <            assertEquals(q.size(), r.size());
537 <            while (!q.isEmpty())
538 <                assertEquals(q.remove(), r.remove());
539 <        } catch(Exception e){
758 <            unexpectedException();
759 <        }
760 <    }
761 <
762 <    /**
763 <     * drainTo(null) throws NPE
764 <     */
765 <    public void testDrainToNull() {
766 <        SynchronousQueue q = new SynchronousQueue();
767 <        try {
768 <            q.drainTo(null);
769 <            shouldThrow();
770 <        } catch(NullPointerException success) {
771 <        }
772 <    }
773 <
774 <    /**
775 <     * drainTo(this) throws IAE
776 <     */
777 <    public void testDrainToSelf() {
778 <        SynchronousQueue q = new SynchronousQueue();
779 <        try {
780 <            q.drainTo(q);
781 <            shouldThrow();
782 <        } catch(IllegalArgumentException success) {
526 >        final SynchronousQueue x = new SynchronousQueue();
527 >        final SynchronousQueue y = new SynchronousQueue(false);
528 >        final SynchronousQueue z = new SynchronousQueue(true);
529 >        assertSerialEquals(x, y);
530 >        assertNotSerialEquals(x, z);
531 >        SynchronousQueue[] qs = { x, y, z };
532 >        for (SynchronousQueue q : qs) {
533 >            SynchronousQueue clone = serialClone(q);
534 >            assertNotSame(q, clone);
535 >            assertSerialEquals(q, clone);
536 >            assertTrue(clone.isEmpty());
537 >            assertEquals(0, clone.size());
538 >            assertEquals(0, clone.remainingCapacity());
539 >            assertFalse(clone.offer(zero));
540          }
541      }
542  
543      /**
544       * drainTo(c) of empty queue doesn't transfer elements
545 <     */
546 <    public void testDrainTo() {
547 <        SynchronousQueue q = new SynchronousQueue();
545 >     */
546 >    public void testDrainTo()      { testDrainTo(false); }
547 >    public void testDrainTo_fair() { testDrainTo(true); }
548 >    public void testDrainTo(boolean fair) {
549 >        final SynchronousQueue q = new SynchronousQueue(fair);
550          ArrayList l = new ArrayList();
551          q.drainTo(l);
552 <        assertEquals(q.size(), 0);
553 <        assertEquals(l.size(), 0);
552 >        assertEquals(0, q.size());
553 >        assertEquals(0, l.size());
554      }
555  
556      /**
557       * drainTo empties queue, unblocking a waiting put.
558 <     */
559 <    public void testDrainToWithActivePut() {
560 <        final SynchronousQueue q = new SynchronousQueue();
561 <        Thread t = new Thread(new Runnable() {
562 <                public void run() {
563 <                    try {
564 <                        q.put(new Integer(1));
565 <                    } catch (InterruptedException ie){
566 <                        threadUnexpectedException();
808 <                    }
809 <                }
810 <            });
811 <        try {
812 <            t.start();
813 <            ArrayList l = new ArrayList();
814 <            Thread.sleep(SHORT_DELAY_MS);
815 <            q.drainTo(l);
816 <            assertTrue(l.size() <= 1);
817 <            if (l.size() > 0)
818 <                assertEquals(l.get(0), new Integer(1));
819 <            t.join();
820 <            assertTrue(l.size() <= 1);
821 <        } catch(Exception e){
822 <            unexpectedException();
823 <        }
824 <    }
825 <
826 <    /**
827 <     * drainTo(null, n) throws NPE
828 <     */
829 <    public void testDrainToNullN() {
830 <        SynchronousQueue q = new SynchronousQueue();
831 <        try {
832 <            q.drainTo(null, 0);
833 <            shouldThrow();
834 <        } catch(NullPointerException success) {
835 <        }
836 <    }
558 >     */
559 >    public void testDrainToWithActivePut()      { testDrainToWithActivePut(false); }
560 >    public void testDrainToWithActivePut_fair() { testDrainToWithActivePut(true); }
561 >    public void testDrainToWithActivePut(boolean fair) {
562 >        final SynchronousQueue q = new SynchronousQueue(fair);
563 >        Thread t = newStartedThread(new CheckedRunnable() {
564 >            public void realRun() throws InterruptedException {
565 >                q.put(one);
566 >            }});
567  
568 <    /**
569 <     * drainTo(this, n) throws IAE
570 <     */
571 <    public void testDrainToSelfN() {
572 <        SynchronousQueue q = new SynchronousQueue();
573 <        try {
574 <            q.drainTo(q, 0);
575 <            shouldThrow();
576 <        } catch(IllegalArgumentException success) {
577 <        }
568 >        ArrayList l = new ArrayList();
569 >        long startTime = System.nanoTime();
570 >        while (l.isEmpty()) {
571 >            q.drainTo(l);
572 >            if (millisElapsedSince(startTime) > LONG_DELAY_MS)
573 >                fail("timed out");
574 >            Thread.yield();
575 >        }
576 >        assertTrue(l.size() == 1);
577 >        assertSame(one, l.get(0));
578 >        awaitTermination(t);
579      }
580  
581      /**
582       * drainTo(c, n) empties up to n elements of queue into c
583 <     */
584 <    public void testDrainToN() {
583 >     */
584 >    public void testDrainToN() throws InterruptedException {
585          final SynchronousQueue q = new SynchronousQueue();
586 <        Thread t1 = new Thread(new Runnable() {
587 <                public void run() {
588 <                    try {
589 <                        q.put(one);
590 <                    } catch (InterruptedException ie){
591 <                        threadUnexpectedException();
592 <                    }
593 <                }
594 <            });
864 <        Thread t2 = new Thread(new Runnable() {
865 <                public void run() {
866 <                    try {
867 <                        q.put(two);
868 <                    } catch (InterruptedException ie){
869 <                        threadUnexpectedException();
870 <                    }
871 <                }
872 <            });
586 >        Thread t1 = newStartedThread(new CheckedRunnable() {
587 >            public void realRun() throws InterruptedException {
588 >                q.put(one);
589 >            }});
590 >
591 >        Thread t2 = newStartedThread(new CheckedRunnable() {
592 >            public void realRun() throws InterruptedException {
593 >                q.put(two);
594 >            }});
595  
596 <        try {
597 <            t1.start();
598 <            t2.start();
599 <            ArrayList l = new ArrayList();
600 <            Thread.sleep(SHORT_DELAY_MS);
601 <            q.drainTo(l, 1);
602 <            assertTrue(l.size() == 1);
603 <            q.drainTo(l, 1);
604 <            assertTrue(l.size() == 2);
605 <            assertTrue(l.contains(one));
884 <            assertTrue(l.contains(two));
885 <            t1.join();
886 <            t2.join();
887 <        } catch(Exception e){
888 <            unexpectedException();
889 <        }
596 >        ArrayList l = new ArrayList();
597 >        delay(SHORT_DELAY_MS);
598 >        q.drainTo(l, 1);
599 >        assertEquals(1, l.size());
600 >        q.drainTo(l, 1);
601 >        assertEquals(2, l.size());
602 >        assertTrue(l.contains(one));
603 >        assertTrue(l.contains(two));
604 >        awaitTermination(t1);
605 >        awaitTermination(t2);
606      }
607  
608 +    /**
609 +     * remove(null), contains(null) always return false
610 +     */
611 +    public void testNeverContainsNull() {
612 +        Collection<?> q = new SynchronousQueue();
613 +        assertFalse(q.contains(null));
614 +        assertFalse(q.remove(null));
615 +    }
616  
617   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines