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.2 by dl, Sun Sep 7 20:39:11 2003 UTC vs.
Revision 1.38 by jsr166, Tue May 31 16:16:24 2011 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.*;
13 <
14 < public class SynchronousQueueTest extends TestCase {
15 <
16 <    private final static int N = 1;
17 <    private static long SHORT_DELAY_MS = 100;
18 <    private static long MEDIUM_DELAY_MS = 1000;
19 <    private static long LONG_DELAY_MS = 10000;
20 <
21 <    public static void main(String[] args) {
22 <        junit.textui.TestRunner.run (suite());  
23 <    }
24 <
25 <    public static Test suite() {
26 <        return new TestSuite(SynchronousQueueTest.class);
27 <    }
27 <
28 <    public void testEmptyFull() {
29 <        SynchronousQueue q = new SynchronousQueue();
30 <        assertTrue(q.isEmpty());
31 <        assertEquals(0, q.size());
32 <        assertEquals(0, q.remainingCapacity());
33 <        assertFalse(q.offer(new Integer(3)));
34 <    }
35 <
36 <    public void testOfferNull(){
37 <        try {
38 <            SynchronousQueue q = new SynchronousQueue();
39 <            q.offer(null);
40 <            fail("should throw NPE");
41 <        } catch (NullPointerException success) { }  
42 <    }
43 <
44 <    public void testOffer(){
45 <        SynchronousQueue q = new SynchronousQueue();
46 <        assertFalse(q.offer(new Integer(1)));
47 <    }
48 <
49 <    public void testAdd(){
50 <        try {
51 <            SynchronousQueue q = new SynchronousQueue();
52 <            assertEquals(0, q.remainingCapacity());
53 <            q.add(new Integer(0));
54 <        } catch (IllegalStateException success){
55 <        }  
56 <    }
57 <
58 <    public void testAddAll1(){
59 <        try {
60 <            SynchronousQueue q = new SynchronousQueue();
61 <            q.addAll(null);
62 <            fail("Cannot add null collection");
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 class Fair extends BlockingQueueTest {
26 >        protected BlockingQueue emptyCollection() {
27 >            return new SynchronousQueue(true);
28          }
64        catch (NullPointerException success) {}
29      }
66    public void testAddAll2(){
67        try {
68            SynchronousQueue q = new SynchronousQueue();
69            Integer[] ints = new Integer[N];
70            q.addAll(Arrays.asList(ints));
71            fail("Cannot add null elements");
72        }
73        catch (NullPointerException success) {}
74    }
75    public void testAddAll4(){
76        try {
77            SynchronousQueue q = new SynchronousQueue();
78            Integer[] ints = new Integer[N];
79            for (int i = 0; i < N; ++i)
80                ints[i] = new Integer(i);
81            q.addAll(Arrays.asList(ints));
82            fail("Cannot add with insufficient capacity");
83        }
84        catch (IllegalStateException success) {}
85    }
86
87    public void testPutNull() {
88        try {
89            SynchronousQueue q = new SynchronousQueue();
90            q.put(null);
91            fail("put should throw NPE");
92        }
93        catch (NullPointerException success){
94        }  
95        catch (InterruptedException ie) {
96            fail("Unexpected exception");
97        }
98     }
30  
31 <    public void testBlockingPut(){
32 <        Thread t = new Thread(new Runnable() {
33 <                public void run() {
103 <                    try {
104 <                        SynchronousQueue q = new SynchronousQueue();
105 <                        q.put(new Integer(0));
106 <                        fail("put should block");
107 <                    } catch (InterruptedException ie){
108 <                    }  
109 <                }});
110 <        t.start();
111 <        try {
112 <           Thread.sleep(SHORT_DELAY_MS);
113 <           t.interrupt();
114 <           t.join();
115 <        }
116 <        catch (InterruptedException ie) {
117 <            fail("Unexpected exception");
31 >    public static class NonFair extends BlockingQueueTest {
32 >        protected BlockingQueue emptyCollection() {
33 >            return new SynchronousQueue(false);
34          }
35      }
36  
37 <    public void testPutWithTake() {
38 <        final SynchronousQueue q = new SynchronousQueue();
123 <        Thread t = new Thread(new Runnable() {
124 <                public void run(){
125 <                    int added = 0;
126 <                    try {
127 <                        q.put(new Object());
128 <                        ++added;
129 <                        q.put(new Object());
130 <                        ++added;
131 <                        q.put(new Object());
132 <                        ++added;
133 <                        q.put(new Object());
134 <                        ++added;
135 <                        fail("Should block");
136 <                    } catch (InterruptedException e){
137 <                        assertTrue(added >= 1);
138 <                    }
139 <                }
140 <            });
141 <        try {
142 <            t.start();
143 <            Thread.sleep(SHORT_DELAY_MS);
144 <            q.take();
145 <            Thread.sleep(SHORT_DELAY_MS);
146 <            t.interrupt();
147 <            t.join();
148 <        } catch (Exception e){
149 <            fail("Unexpected exception");
150 <        }
151 <    }
152 <
153 <    public void testTimedOffer() {
154 <        final SynchronousQueue q = new SynchronousQueue();
155 <        Thread t = new Thread(new Runnable() {
156 <                public void run(){
157 <                    try {
158 <
159 <                        assertFalse(q.offer(new Object(), SHORT_DELAY_MS/2, TimeUnit.MILLISECONDS));
160 <                        q.offer(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
161 <                        fail("Should block");
162 <                    } catch (InterruptedException success){}
163 <                }
164 <            });
165 <        
166 <        try {
167 <            t.start();
168 <            Thread.sleep(SHORT_DELAY_MS);
169 <            t.interrupt();
170 <            t.join();
171 <        } catch (Exception e){
172 <            fail("Unexpected exception");
173 <        }
37 >    public static void main(String[] args) {
38 >        junit.textui.TestRunner.run(suite());
39      }
40  
41 <
42 <    public void testTakeFromEmpty() {
43 <        final SynchronousQueue q = new SynchronousQueue();
44 <        Thread t = new Thread(new Runnable() {
180 <                public void run(){
181 <                    try {
182 <                        q.take();
183 <                        fail("Should block");
184 <                    } catch (InterruptedException success){ }                
185 <                }
186 <            });
187 <        try {
188 <            t.start();
189 <            Thread.sleep(SHORT_DELAY_MS);
190 <            t.interrupt();
191 <            t.join();
192 <        } catch (Exception e){
193 <            fail("Unexpected exception");
194 <        }
41 >    public static Test suite() {
42 >        return newTestSuite(SynchronousQueueTest.class,
43 >                            new Fair().testSuite(),
44 >                            new NonFair().testSuite());
45      }
46  
47 <    public void testPoll(){
48 <        SynchronousQueue q = new SynchronousQueue();
49 <        assertNull(q.poll());
47 >    /**
48 >     * Any SynchronousQueue is both empty and full
49 >     */
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 <    public void testTimedPoll0() {
60 >    /**
61 >     * offer fails if no active taker
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 >     * add throws IllegalStateException if no active taker
72 >     */
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();
80 <            assertNull(q.poll(0, TimeUnit.MILLISECONDS));
81 <        } catch (InterruptedException e){
82 <            fail("Unexpected exception");
83 <        }  
84 <    }
79 >            q.add(one);
80 >            shouldThrow();
81 >        } catch (IllegalStateException success) {}
82 >    }
83 >
84 >    /**
85 >     * addAll(this) throws IllegalArgumentException
86 >     */
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 >            q.addAll(q);
93 >            shouldThrow();
94 >        } catch (IllegalArgumentException success) {}
95 >    }
96 >
97 >    /**
98 >     * addAll throws ISE if no active taker
99 >     */
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 >            q.addAll(coll);
110 >            shouldThrow();
111 >        } catch (IllegalStateException success) {}
112 >    }
113 >
114 >    /**
115 >     * put blocks interruptibly if no active taker
116 >     */
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 <    public void testTimedPoll() {
132 <        try {
133 <            SynchronousQueue q = new SynchronousQueue();
134 <            assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
135 <        } catch (InterruptedException e){
136 <            fail("Unexpected exception");
137 <        }  
138 <    }
139 <
140 <    public void testInterruptedTimedPoll(){
141 <        Thread t = new Thread(new Runnable() {
142 <                public void run() {
143 <                    try {
224 <                        SynchronousQueue q = new SynchronousQueue();
225 <                        assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
226 <                    } catch (InterruptedException success){
227 <                    }  
228 <                }});
229 <        t.start();
230 <        try {
231 <           Thread.sleep(SHORT_DELAY_MS);
232 <           t.interrupt();
233 <           t.join();
234 <        }
235 <        catch (InterruptedException ie) {
236 <            fail("Unexpected exception");
237 <        }
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 <    public void testTimedPollWithOffer(){
147 <        final SynchronousQueue q = new SynchronousQueue();
148 <        Thread t = new Thread(new Runnable() {
149 <                public void run(){
150 <                    try {
151 <                        assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
152 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
153 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
154 <                        fail("Should block");
155 <                    } catch (InterruptedException success) { }                
156 <                }
157 <            });
158 <        try {
253 <            t.start();
254 <            Thread.sleep(SHORT_DELAY_MS * 2);
255 <            assertTrue(q.offer(new Integer(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
256 <            t.interrupt();
257 <            t.join();
258 <        } catch (Exception e){
259 <            fail("Unexpected exception");
260 <        }
261 <    }  
146 >    /**
147 >     * put blocks interruptibly waiting for take
148 >     */
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 +                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(q.remainingCapacity(), 0);
170 +        try { assertSame(one, q.take()); }
171 +        catch (InterruptedException e) { threadUnexpectedException(e); }
172 +
173 +        await(pleaseInterrupt);
174 +        assertThreadStaysAlive(t);
175 +        t.interrupt();
176 +        awaitTermination(t);
177 +        assertEquals(q.remainingCapacity(), 0);
178 +    }
179 +
180 +    /**
181 +     * timed offer times out if elements not taken
182 +     */
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 +     * poll return null if no active putter
208 +     */
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 +     * timed poll with zero timeout times out if no active putter
218 +     */
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 +     * 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 +     * timed poll before a delayed offer times out, returning null;
242 +     * after offer succeeds; on interruption throws
243 +     */
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 <    public void testPeek(){
262 <        SynchronousQueue q = new SynchronousQueue();
263 <        assertNull(q.peek());
264 <    }
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 <    public void testElement(){
269 <        SynchronousQueue q = new SynchronousQueue();
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 >     * peek() returns null if no active putter
290 >     */
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 >     * element() throws NoSuchElementException if no active putter
300 >     */
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 <            fail("no such element");
308 <        }
275 <        catch (NoSuchElementException success) {}
307 >            shouldThrow();
308 >        } catch (NoSuchElementException success) {}
309      }
310  
311 <    public void testRemove(){
312 <        SynchronousQueue q = new SynchronousQueue();
311 >    /**
312 >     * remove() throws NoSuchElementException if no active putter
313 >     */
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 <            fail("remove should throw");
321 <        } catch (NoSuchElementException success){
284 <        }  
320 >            shouldThrow();
321 >        } catch (NoSuchElementException success) {}
322      }
323  
324 <    public void testRemoveElement(){
325 <        SynchronousQueue q = new SynchronousQueue();
326 <        for (int i = 1; i < N; i+=2) {
327 <            assertFalse(q.remove(new Integer(i)));
328 <        }
324 >    /**
325 >     * remove(x) returns false
326 >     */
327 >    public void testRemoveElement()      { testRemoveElement(false); }
328 >    public void testRemoveElement_fair() { testRemoveElement(true); }
329 >    public void testRemoveElement(boolean fair) {
330 >        final SynchronousQueue q = new SynchronousQueue(fair);
331 >        assertFalse(q.remove(zero));
332          assertTrue(q.isEmpty());
333      }
294        
295    public void testContains(){
296        SynchronousQueue q = new SynchronousQueue();
297        for (int i = 0; i < N; ++i) {
298            assertFalse(q.contains(new Integer(i)));
299        }
300    }
334  
335 <    public void testClear(){
336 <        SynchronousQueue q = new SynchronousQueue();
335 >    /**
336 >     * contains returns false
337 >     */
338 >    public void testContains()      { testContains(false); }
339 >    public void testContains_fair() { testContains(true); }
340 >    public void testContains(boolean fair) {
341 >        final SynchronousQueue q = new SynchronousQueue(fair);
342 >        assertFalse(q.contains(zero));
343 >    }
344 >
345 >    /**
346 >     * clear ensures isEmpty
347 >     */
348 >    public void testClear()      { testClear(false); }
349 >    public void testClear_fair() { testClear(true); }
350 >    public void testClear(boolean fair) {
351 >        final SynchronousQueue q = new SynchronousQueue(fair);
352          q.clear();
353          assertTrue(q.isEmpty());
354      }
355  
356 <    public void testContainsAll(){
357 <        SynchronousQueue q = new SynchronousQueue();
356 >    /**
357 >     * containsAll returns false unless empty
358 >     */
359 >    public void testContainsAll()      { testContainsAll(false); }
360 >    public void testContainsAll_fair() { testContainsAll(true); }
361 >    public void testContainsAll(boolean fair) {
362 >        final SynchronousQueue q = new SynchronousQueue(fair);
363          Integer[] empty = new Integer[0];
364 <        Integer[] ints = new Integer[1]; ints[0] = new Integer(0);
365 <        //        assertTrue(q.containsAll(Arrays.asList(empty)));
364 >        assertTrue(q.containsAll(Arrays.asList(empty)));
365 >        Integer[] ints = new Integer[1]; ints[0] = zero;
366          assertFalse(q.containsAll(Arrays.asList(ints)));
367      }
368  
369 <    public void testRetainAll(){
370 <        SynchronousQueue q = new SynchronousQueue();
369 >    /**
370 >     * retainAll returns false
371 >     */
372 >    public void testRetainAll()      { testRetainAll(false); }
373 >    public void testRetainAll_fair() { testRetainAll(true); }
374 >    public void testRetainAll(boolean fair) {
375 >        final SynchronousQueue q = new SynchronousQueue(fair);
376          Integer[] empty = new Integer[0];
377 <        Integer[] ints = new Integer[1]; ints[0] = new Integer(0);
378 <        q.retainAll(Arrays.asList(ints));
379 <        //        assertTrue(q.containsAll(Arrays.asList(empty)));
322 <        assertFalse(q.containsAll(Arrays.asList(ints)));
377 >        assertFalse(q.retainAll(Arrays.asList(empty)));
378 >        Integer[] ints = new Integer[1]; ints[0] = zero;
379 >        assertFalse(q.retainAll(Arrays.asList(ints)));
380      }
381  
382 <    public void testRemoveAll(){
383 <        SynchronousQueue q = new SynchronousQueue();
382 >    /**
383 >     * removeAll returns false
384 >     */
385 >    public void testRemoveAll()      { testRemoveAll(false); }
386 >    public void testRemoveAll_fair() { testRemoveAll(true); }
387 >    public void testRemoveAll(boolean fair) {
388 >        final SynchronousQueue q = new SynchronousQueue(fair);
389          Integer[] empty = new Integer[0];
390 <        Integer[] ints = new Integer[1]; ints[0] = new Integer(0);
391 <        q.removeAll(Arrays.asList(ints));
330 <        //        assertTrue(q.containsAll(Arrays.asList(empty)));
390 >        assertFalse(q.removeAll(Arrays.asList(empty)));
391 >        Integer[] ints = new Integer[1]; ints[0] = zero;
392          assertFalse(q.containsAll(Arrays.asList(ints)));
393      }
394  
395 <
396 <    public void testToArray(){
397 <        SynchronousQueue q = new SynchronousQueue();
398 <        Object[] o = q.toArray();
395 >    /**
396 >     * toArray is empty
397 >     */
398 >    public void testToArray()      { testToArray(false); }
399 >    public void testToArray_fair() { testToArray(true); }
400 >    public void testToArray(boolean fair) {
401 >        final SynchronousQueue q = new SynchronousQueue(fair);
402 >        Object[] o = q.toArray();
403          assertEquals(o.length, 0);
404      }
405  
406 <    public void testToArray2(){
407 <        SynchronousQueue q = new SynchronousQueue();
408 <        Integer[] ints = new Integer[1];
406 >    /**
407 >     * toArray(a) is nulled at position 0
408 >     */
409 >    public void testToArray2()      { testToArray2(false); }
410 >    public void testToArray2_fair() { testToArray2(true); }
411 >    public void testToArray2(boolean fair) {
412 >        final SynchronousQueue q = new SynchronousQueue(fair);
413 >        Integer[] ints = new Integer[1];
414          assertNull(ints[0]);
415      }
416 <    
417 <    public void testIterator(){
418 <        SynchronousQueue q = new SynchronousQueue();
419 <        Iterator it = q.iterator();
416 >
417 >    /**
418 >     * toArray(null) throws NPE
419 >     */
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 >
430 >    /**
431 >     * iterator does not traverse any elements
432 >     */
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 <            fail("should throw");
442 <        }
355 <        catch (NoSuchElementException success) {}
441 >            shouldThrow();
442 >        } catch (NoSuchElementException success) {}
443      }
444  
445 <    public void testIteratorRemove(){
446 <        SynchronousQueue q = new SynchronousQueue();
447 <        Iterator it = q.iterator();
445 >    /**
446 >     * iterator remove throws ISE
447 >     */
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 <            fail("should throw");
456 <        }
365 <        catch (IllegalStateException success) {}
455 >            shouldThrow();
456 >        } catch (IllegalStateException success) {}
457      }
458  
459 <    public void testToString(){
460 <        SynchronousQueue q = new SynchronousQueue();
459 >    /**
460 >     * toString returns a non-null string
461 >     */
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 <    }        
373 <
467 >        assertNotNull(s);
468 >    }
469  
470 <    public void testOfferInExecutor() {
471 <        final SynchronousQueue q = new SynchronousQueue();
470 >    /**
471 >     * offer transfers elements across Executor tasks
472 >     */
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() {
480 >        executor.execute(new CheckedRunnable() {
481 >            public void realRun() throws InterruptedException {
482                  assertFalse(q.offer(one));
483 <                try {
484 <                    assertTrue(q.offer(one, MEDIUM_DELAY_MS * 2, TimeUnit.MILLISECONDS));
485 <                    assertEquals(0, q.remainingCapacity());
486 <                }
487 <                catch (InterruptedException e) {
488 <                    fail("should not be interrupted");
489 <                }
490 <            }
491 <        });
492 <
493 <        executor.execute(new Runnable() {
494 <            public void run() {
495 <                try {
496 <                    Thread.sleep(MEDIUM_DELAY_MS);
497 <                    assertEquals(one, q.take());
498 <                }
499 <                catch (InterruptedException e) {
500 <                    fail("should not be interrupted");
501 <                }
502 <            }
503 <        });
504 <        
405 <        executor.shutdown();
406 <
407 <    }
408 <
409 <    public void testPollInExecutor() {
410 <
411 <        final SynchronousQueue q = new SynchronousQueue();
412 <
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 >
494 >        joinPool(executor);
495 >    }
496 >
497 >    /**
498 >     * timed poll retrieves elements across Executor threads
499 >     */
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 <
507 <        executor.execute(new Runnable() {
416 <            public void run() {
506 >        executor.execute(new CheckedRunnable() {
507 >            public void realRun() throws InterruptedException {
508                  assertNull(q.poll());
509 <                try {
510 <                    assertTrue(null != q.poll(MEDIUM_DELAY_MS * 2, TimeUnit.MILLISECONDS));
511 <                    assertTrue(q.isEmpty());
512 <                }
513 <                catch (InterruptedException e) {
514 <                    fail("should not be interrupted");
515 <                }
516 <            }
517 <        });
518 <
519 <        executor.execute(new Runnable() {
520 <            public void run() {
521 <                try {
522 <                    Thread.sleep(MEDIUM_DELAY_MS);
523 <                    q.put(new Integer(1));
524 <                }
525 <                catch (InterruptedException e) {
526 <                    fail("should not be interrupted");
527 <                }
528 <            }
529 <        });
530 <        
531 <        executor.shutdown();
532 <
533 <    }
534 <
535 <    public void testSerialization() {
536 <        SynchronousQueue q = new SynchronousQueue();
537 <        try {
538 <            ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
539 <            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
540 <            out.writeObject(q);
541 <            out.close();
542 <
543 <            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
544 <            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
545 <            SynchronousQueue r = (SynchronousQueue)in.readObject();
546 <            assertEquals(q.size(), r.size());
547 <            while (!q.isEmpty())
548 <                assertEquals(q.remove(), r.remove());
549 <        } catch(Exception e){
550 <            fail("unexpected exception");
551 <        }
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 >
520 >        joinPool(executor);
521 >    }
522 >
523 >    /**
524 >     * a deserialized serialized queue is usable
525 >     */
526 >    public void testSerialization()      { testSerialization(false); }
527 >    public void testSerialization_fair() { testSerialization(true); }
528 >    public void testSerialization(boolean fair) {
529 >        final SynchronousQueue x = new SynchronousQueue(fair);
530 >        final SynchronousQueue y = serialClone(x);
531 >        assertTrue(x != y);
532 >        assertTrue(x.isEmpty());
533 >        assertTrue(y.isEmpty());
534 >    }
535 >
536 >    /**
537 >     * drainTo(c) of empty queue doesn't transfer elements
538 >     */
539 >    public void testDrainTo()      { testDrainTo(false); }
540 >    public void testDrainTo_fair() { testDrainTo(true); }
541 >    public void testDrainTo(boolean fair) {
542 >        final SynchronousQueue q = new SynchronousQueue(fair);
543 >        ArrayList l = new ArrayList();
544 >        q.drainTo(l);
545 >        assertEquals(q.size(), 0);
546 >        assertEquals(l.size(), 0);
547 >    }
548 >
549 >    /**
550 >     * drainTo empties queue, unblocking a waiting put.
551 >     */
552 >    public void testDrainToWithActivePut()      { testDrainToWithActivePut(false); }
553 >    public void testDrainToWithActivePut_fair() { testDrainToWithActivePut(true); }
554 >    public void testDrainToWithActivePut(boolean fair) {
555 >        final SynchronousQueue q = new SynchronousQueue(fair);
556 >        Thread t = newStartedThread(new CheckedRunnable() {
557 >            public void realRun() throws InterruptedException {
558 >                q.put(one);
559 >            }});
560 >
561 >        ArrayList l = new ArrayList();
562 >        long startTime = System.nanoTime();
563 >        while (l.isEmpty()) {
564 >            q.drainTo(l);
565 >            if (millisElapsedSince(startTime) > LONG_DELAY_MS)
566 >                fail("timed out");
567 >            Thread.yield();
568 >        }
569 >        assertTrue(l.size() == 1);
570 >        assertSame(one, l.get(0));
571 >        awaitTermination(t);
572 >    }
573 >
574 >    /**
575 >     * drainTo(c, n) empties up to n elements of queue into c
576 >     */
577 >    public void testDrainToN() throws InterruptedException {
578 >        final SynchronousQueue q = new SynchronousQueue();
579 >        Thread t1 = newStartedThread(new CheckedRunnable() {
580 >            public void realRun() throws InterruptedException {
581 >                q.put(one);
582 >            }});
583 >
584 >        Thread t2 = newStartedThread(new CheckedRunnable() {
585 >            public void realRun() throws InterruptedException {
586 >                q.put(two);
587 >            }});
588 >
589 >        ArrayList l = new ArrayList();
590 >        delay(SHORT_DELAY_MS);
591 >        q.drainTo(l, 1);
592 >        assertEquals(1, l.size());
593 >        q.drainTo(l, 1);
594 >        assertEquals(2, l.size());
595 >        assertTrue(l.contains(one));
596 >        assertTrue(l.contains(two));
597 >        awaitTermination(t1);
598 >        awaitTermination(t2);
599      }
600  
601   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines