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.4 by dl, Sat Sep 20 18:20:08 2003 UTC vs.
Revision 1.42 by jsr166, Sun Nov 23 22:27:06 2014 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines