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

Comparing jsr166/src/test/tck/LinkedBlockingQueueTest.java (file contents):
Revision 1.2 by dl, Sun Sep 7 20:39:11 2003 UTC vs.
Revision 1.58 by jsr166, Sat Feb 28 19:59:23 2015 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 LinkedBlockingQueueTest extends TestCase {
15 <
16 <    private static int N = 10;
17 <    private static long SHORT_DELAY_MS = 100;
18 <    private static long MEDIUM_DELAY_MS = 1000;
19 <    private static long LONG_DELAY_MS = 10000;
9 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 >
11 > import java.util.ArrayList;
12 > import java.util.Arrays;
13 > import java.util.Collection;
14 > import java.util.Iterator;
15 > import java.util.NoSuchElementException;
16 > import java.util.Queue;
17 > import java.util.concurrent.BlockingQueue;
18 > import java.util.concurrent.CountDownLatch;
19 > import java.util.concurrent.Executors;
20 > import java.util.concurrent.ExecutorService;
21 > import java.util.concurrent.LinkedBlockingQueue;
22 >
23 > import junit.framework.Test;
24 >
25 > public class LinkedBlockingQueueTest extends JSR166TestCase {
26 >
27 >    public static class Unbounded extends BlockingQueueTest {
28 >        protected BlockingQueue emptyCollection() {
29 >            return new LinkedBlockingQueue();
30 >        }
31 >    }
32 >
33 >    public static class Bounded extends BlockingQueueTest {
34 >        protected BlockingQueue emptyCollection() {
35 >            return new LinkedBlockingQueue(SIZE);
36 >        }
37 >    }
38  
39      public static void main(String[] args) {
40 <        junit.textui.TestRunner.run (suite());  
40 >        junit.textui.TestRunner.run(suite());
41      }
42  
43      public static Test suite() {
44 <        return new TestSuite(LinkedBlockingQueueTest.class);
44 >        return newTestSuite(LinkedBlockingQueueTest.class,
45 >                            new Unbounded().testSuite(),
46 >                            new Bounded().testSuite());
47      }
48  
49      /**
50 <     * Create a queue of given size containing consecutive
50 >     * Returns a new queue of given size containing consecutive
51       * Integers 0 ... n.
52       */
53 <    private LinkedBlockingQueue fullQueue(int n) {
54 <        LinkedBlockingQueue q = new LinkedBlockingQueue(n);
53 >    private LinkedBlockingQueue<Integer> populatedQueue(int n) {
54 >        LinkedBlockingQueue<Integer> q =
55 >            new LinkedBlockingQueue<Integer>(n);
56          assertTrue(q.isEmpty());
57 <        for(int i = 0; i < n; i++)
58 <            assertTrue(q.offer(new Integer(i)));
57 >        for (int i = 0; i < n; i++)
58 >            assertTrue(q.offer(new Integer(i)));
59          assertFalse(q.isEmpty());
60          assertEquals(0, q.remainingCapacity());
61 <        assertEquals(n, q.size());
61 >        assertEquals(n, q.size());
62          return q;
63      }
64 <
65 <    public void testConstructor1(){
66 <        assertEquals(N, new LinkedBlockingQueue(N).remainingCapacity());
64 >
65 >    /**
66 >     * A new queue has the indicated capacity, or Integer.MAX_VALUE if
67 >     * none given
68 >     */
69 >    public void testConstructor1() {
70 >        assertEquals(SIZE, new LinkedBlockingQueue(SIZE).remainingCapacity());
71 >        assertEquals(Integer.MAX_VALUE, new LinkedBlockingQueue().remainingCapacity());
72      }
73  
74 <    public void testConstructor2(){
74 >    /**
75 >     * Constructor throws IllegalArgumentException if capacity argument nonpositive
76 >     */
77 >    public void testConstructor2() {
78          try {
79 <            LinkedBlockingQueue q = new LinkedBlockingQueue(0);
80 <            fail("Cannot make zero-sized");
81 <        }
52 <        catch (IllegalArgumentException success) {}
79 >            new LinkedBlockingQueue(0);
80 >            shouldThrow();
81 >        } catch (IllegalArgumentException success) {}
82      }
83  
84 <    public void testConstructor3(){
85 <
84 >    /**
85 >     * Initializing from null Collection throws NullPointerException
86 >     */
87 >    public void testConstructor3() {
88          try {
89 <            LinkedBlockingQueue q = new LinkedBlockingQueue(null);
90 <            fail("Cannot make from null collection");
91 <        }
61 <        catch (NullPointerException success) {}
89 >            new LinkedBlockingQueue(null);
90 >            shouldThrow();
91 >        } catch (NullPointerException success) {}
92      }
93  
94 <    public void testConstructor4(){
94 >    /**
95 >     * Initializing from Collection of null elements throws NullPointerException
96 >     */
97 >    public void testConstructor4() {
98 >        Collection<Integer> elements = Arrays.asList(new Integer[SIZE]);
99          try {
100 <            Integer[] ints = new Integer[N];
101 <            LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
102 <            fail("Cannot make with null elements");
69 <        }
70 <        catch (NullPointerException success) {}
100 >            new LinkedBlockingQueue(elements);
101 >            shouldThrow();
102 >        } catch (NullPointerException success) {}
103      }
104  
105 <    public void testConstructor5(){
106 <        try {
107 <            Integer[] ints = new Integer[N];
108 <            for (int i = 0; i < N-1; ++i)
109 <                ints[i] = new Integer(i);
110 <            LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
111 <            fail("Cannot make with null elements");
112 <        }
113 <        catch (NullPointerException success) {}
105 >    /**
106 >     * Initializing from Collection with some null elements throws
107 >     * NullPointerException
108 >     */
109 >    public void testConstructor5() {
110 >        Integer[] ints = new Integer[SIZE];
111 >        for (int i = 0; i < SIZE-1; ++i)
112 >            ints[i] = new Integer(i);
113 >        Collection<Integer> elements = Arrays.asList(ints);
114 >        try {
115 >            new LinkedBlockingQueue(elements);
116 >            shouldThrow();
117 >        } catch (NullPointerException success) {}
118      }
119  
120 <    public void testConstructor6(){
121 <        try {
122 <            Integer[] ints = new Integer[N];
123 <            for (int i = 0; i < N; ++i)
124 <                ints[i] = new Integer(i);
125 <            LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
126 <            for (int i = 0; i < N; ++i)
127 <                assertEquals(ints[i], q.poll());
128 <        }
129 <        finally {}
120 >    /**
121 >     * Queue contains all elements of collection used to initialize
122 >     */
123 >    public void testConstructor6() {
124 >        Integer[] ints = new Integer[SIZE];
125 >        for (int i = 0; i < SIZE; ++i)
126 >            ints[i] = new Integer(i);
127 >        LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
128 >        for (int i = 0; i < SIZE; ++i)
129 >            assertEquals(ints[i], q.poll());
130      }
131  
132 +    /**
133 +     * Queue transitions from empty to full when elements added
134 +     */
135      public void testEmptyFull() {
136          LinkedBlockingQueue q = new LinkedBlockingQueue(2);
137          assertTrue(q.isEmpty());
138          assertEquals("should have room for 2", 2, q.remainingCapacity());
139 <        q.add(new Integer(1));
139 >        q.add(one);
140          assertFalse(q.isEmpty());
141 <        q.add(new Integer(2));
141 >        q.add(two);
142          assertFalse(q.isEmpty());
143 <        assertEquals("queue should be full", 0, q.remainingCapacity());
144 <        assertFalse("offer should be rejected", q.offer(new Integer(3)));
143 >        assertEquals(0, q.remainingCapacity());
144 >        assertFalse(q.offer(three));
145      }
146  
147 <    public void testRemainingCapacity(){
148 <        LinkedBlockingQueue q = fullQueue(N);
149 <        for (int i = 0; i < N; ++i) {
147 >    /**
148 >     * remainingCapacity decreases on add, increases on remove
149 >     */
150 >    public void testRemainingCapacity() {
151 >        BlockingQueue q = populatedQueue(SIZE);
152 >        for (int i = 0; i < SIZE; ++i) {
153              assertEquals(i, q.remainingCapacity());
154 <            assertEquals(N-i, q.size());
155 <            q.remove();
154 >            assertEquals(SIZE, q.size() + q.remainingCapacity());
155 >            assertEquals(i, q.remove());
156          }
157 <        for (int i = 0; i < N; ++i) {
158 <            assertEquals(N-i, q.remainingCapacity());
159 <            assertEquals(i, q.size());
160 <            q.add(new Integer(i));
157 >        for (int i = 0; i < SIZE; ++i) {
158 >            assertEquals(SIZE-i, q.remainingCapacity());
159 >            assertEquals(SIZE, q.size() + q.remainingCapacity());
160 >            assertTrue(q.add(i));
161          }
162      }
163  
164 <    public void testOfferNull(){
165 <        try {
166 <            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
167 <            q.offer(null);
168 <            fail("should throw NPE");
169 <        } catch (NullPointerException success) { }  
164 >    /**
165 >     * Offer succeeds if not full; fails if full
166 >     */
167 >    public void testOffer() {
168 >        LinkedBlockingQueue q = new LinkedBlockingQueue(1);
169 >        assertTrue(q.offer(zero));
170 >        assertFalse(q.offer(one));
171      }
172  
173 <    public void testOffer(){
174 <        LinkedBlockingQueue q = new LinkedBlockingQueue(1);
175 <        assertTrue(q.offer(new Integer(0)));
176 <        assertFalse(q.offer(new Integer(1)));
173 >    /**
174 >     * add succeeds if not full; throws IllegalStateException if full
175 >     */
176 >    public void testAdd() {
177 >        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
178 >        for (int i = 0; i < SIZE; ++i)
179 >            assertTrue(q.add(new Integer(i)));
180 >        assertEquals(0, q.remainingCapacity());
181 >        try {
182 >            q.add(new Integer(SIZE));
183 >            shouldThrow();
184 >        } catch (IllegalStateException success) {}
185      }
186  
187 <    public void testAdd(){
188 <        try {
189 <            LinkedBlockingQueue q = new LinkedBlockingQueue(N);
190 <            for (int i = 0; i < N; ++i) {
191 <                assertTrue(q.add(new Integer(i)));
192 <            }
193 <            assertEquals(0, q.remainingCapacity());
194 <            q.add(new Integer(N));
195 <        } catch (IllegalStateException success){
196 <        }  
197 <    }
198 <
199 <    public void testAddAll1(){
200 <        try {
201 <            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
202 <            q.addAll(null);
203 <            fail("Cannot add null collection");
204 <        }
205 <        catch (NullPointerException success) {}
206 <    }
207 <    public void testAddAll2(){
208 <        try {
209 <            LinkedBlockingQueue q = new LinkedBlockingQueue(N);
210 <            Integer[] ints = new Integer[N];
211 <            q.addAll(Arrays.asList(ints));
212 <            fail("Cannot add null elements");
213 <        }
214 <        catch (NullPointerException success) {}
215 <    }
216 <    public void testAddAll3(){
217 <        try {
218 <            LinkedBlockingQueue q = new LinkedBlockingQueue(N);
219 <            Integer[] ints = new Integer[N];
220 <            for (int i = 0; i < N-1; ++i)
221 <                ints[i] = new Integer(i);
222 <            q.addAll(Arrays.asList(ints));
223 <            fail("Cannot add null elements");
224 <        }
225 <        catch (NullPointerException success) {}
226 <    }
227 <    public void testAddAll4(){
228 <        try {
229 <            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
230 <            Integer[] ints = new Integer[N];
231 <            for (int i = 0; i < N; ++i)
232 <                ints[i] = new Integer(i);
233 <            q.addAll(Arrays.asList(ints));
234 <            fail("Cannot add with insufficient capacity");
235 <        }
236 <        catch (IllegalStateException success) {}
237 <    }
238 <    public void testAddAll5(){
239 <        try {
240 <            Integer[] empty = new Integer[0];
241 <            Integer[] ints = new Integer[N];
242 <            for (int i = 0; i < N; ++i)
243 <                ints[i] = new Integer(i);
244 <            LinkedBlockingQueue q = new LinkedBlockingQueue(N);
245 <            assertFalse(q.addAll(Arrays.asList(empty)));
246 <            assertTrue(q.addAll(Arrays.asList(ints)));
247 <            for (int i = 0; i < N; ++i)
248 <                assertEquals(ints[i], q.poll());
249 <        }
250 <        finally {}
251 <    }
252 <
202 <     public void testPutNull() {
203 <        try {
204 <            LinkedBlockingQueue q = new LinkedBlockingQueue(N);
205 <            q.put(null);
206 <            fail("put should throw NPE");
207 <        }
208 <        catch (NullPointerException success){
209 <        }  
210 <        catch (InterruptedException ie) {
211 <            fail("Unexpected exception");
212 <        }
213 <     }
214 <
215 <     public void testPut() {
216 <         try {
217 <             LinkedBlockingQueue q = new LinkedBlockingQueue(N);
218 <             for (int i = 0; i < N; ++i) {
219 <                 Integer I = new Integer(i);
220 <                 q.put(I);
221 <                 assertTrue(q.contains(I));
222 <             }
223 <             assertEquals(0, q.remainingCapacity());
224 <         }
225 <        catch (InterruptedException ie) {
226 <            fail("Unexpected exception");
227 <        }
228 <    }
229 <
230 <    public void testBlockingPut(){
231 <        Thread t = new Thread(new Runnable() {
232 <                public void run() {
233 <                    int added = 0;
234 <                    try {
235 <                        LinkedBlockingQueue q = new LinkedBlockingQueue(N);
236 <                        for (int i = 0; i < N; ++i) {
237 <                            q.put(new Integer(i));
238 <                            ++added;
239 <                        }
240 <                        q.put(new Integer(N));
241 <                        fail("put should block");
242 <                    } catch (InterruptedException ie){
243 <                        assertEquals(added, N);
244 <                    }  
245 <                }});
246 <        t.start();
247 <        try {
248 <           Thread.sleep(SHORT_DELAY_MS);
249 <           t.interrupt();
250 <           t.join();
251 <        }
252 <        catch (InterruptedException ie) {
253 <            fail("Unexpected exception");
187 >    /**
188 >     * addAll(this) throws IllegalArgumentException
189 >     */
190 >    public void testAddAllSelf() {
191 >        LinkedBlockingQueue q = populatedQueue(SIZE);
192 >        try {
193 >            q.addAll(q);
194 >            shouldThrow();
195 >        } catch (IllegalArgumentException success) {}
196 >    }
197 >
198 >    /**
199 >     * addAll of a collection with any null elements throws NPE after
200 >     * possibly adding some elements
201 >     */
202 >    public void testAddAll3() {
203 >        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
204 >        Integer[] ints = new Integer[SIZE];
205 >        for (int i = 0; i < SIZE-1; ++i)
206 >            ints[i] = new Integer(i);
207 >        Collection<Integer> elements = Arrays.asList(ints);
208 >        try {
209 >            q.addAll(elements);
210 >            shouldThrow();
211 >        } catch (NullPointerException success) {}
212 >    }
213 >
214 >    /**
215 >     * addAll throws IllegalStateException if not enough room
216 >     */
217 >    public void testAddAll4() {
218 >        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE - 1);
219 >        Integer[] ints = new Integer[SIZE];
220 >        for (int i = 0; i < SIZE; ++i)
221 >            ints[i] = new Integer(i);
222 >        Collection<Integer> elements = Arrays.asList(ints);
223 >        try {
224 >            q.addAll(elements);
225 >            shouldThrow();
226 >        } catch (IllegalStateException success) {}
227 >    }
228 >
229 >    /**
230 >     * Queue contains all elements, in traversal order, of successful addAll
231 >     */
232 >    public void testAddAll5() {
233 >        Integer[] empty = new Integer[0];
234 >        Integer[] ints = new Integer[SIZE];
235 >        for (int i = 0; i < SIZE; ++i)
236 >            ints[i] = new Integer(i);
237 >        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
238 >        assertFalse(q.addAll(Arrays.asList(empty)));
239 >        assertTrue(q.addAll(Arrays.asList(ints)));
240 >        for (int i = 0; i < SIZE; ++i)
241 >            assertEquals(ints[i], q.poll());
242 >    }
243 >
244 >    /**
245 >     * all elements successfully put are contained
246 >     */
247 >    public void testPut() throws InterruptedException {
248 >        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
249 >        for (int i = 0; i < SIZE; ++i) {
250 >            Integer x = new Integer(i);
251 >            q.put(x);
252 >            assertTrue(q.contains(x));
253          }
254 +        assertEquals(0, q.remainingCapacity());
255 +    }
256 +
257 +    /**
258 +     * put blocks interruptibly if full
259 +     */
260 +    public void testBlockingPut() throws InterruptedException {
261 +        final LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
262 +        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
263 +        Thread t = newStartedThread(new CheckedRunnable() {
264 +            public void realRun() throws InterruptedException {
265 +                for (int i = 0; i < SIZE; ++i)
266 +                    q.put(i);
267 +                assertEquals(SIZE, q.size());
268 +                assertEquals(0, q.remainingCapacity());
269 +
270 +                Thread.currentThread().interrupt();
271 +                try {
272 +                    q.put(99);
273 +                    shouldThrow();
274 +                } catch (InterruptedException success) {}
275 +                assertFalse(Thread.interrupted());
276 +
277 +                pleaseInterrupt.countDown();
278 +                try {
279 +                    q.put(99);
280 +                    shouldThrow();
281 +                } catch (InterruptedException success) {}
282 +                assertFalse(Thread.interrupted());
283 +            }});
284 +
285 +        await(pleaseInterrupt);
286 +        assertThreadStaysAlive(t);
287 +        t.interrupt();
288 +        awaitTermination(t);
289 +        assertEquals(SIZE, q.size());
290 +        assertEquals(0, q.remainingCapacity());
291      }
292  
293 <    public void testPutWithTake() {
293 >    /**
294 >     * put blocks interruptibly waiting for take when full
295 >     */
296 >    public void testPutWithTake() throws InterruptedException {
297 >        final int capacity = 2;
298          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
299 <        Thread t = new Thread(new Runnable() {
300 <                public void run(){
301 <                    int added = 0;
302 <                    try {
303 <                        q.put(new Object());
304 <                        ++added;
305 <                        q.put(new Object());
306 <                        ++added;
307 <                        q.put(new Object());
308 <                        ++added;
309 <                        q.put(new Object());
310 <                        ++added;
311 <                        fail("Should block");
312 <                    } catch (InterruptedException e){
313 <                        assertTrue(added >= 2);
314 <                    }
315 <                }
316 <            });
317 <        try {
318 <            t.start();
319 <            Thread.sleep(SHORT_DELAY_MS);
320 <            q.take();
321 <            t.interrupt();
322 <            t.join();
323 <        } catch (Exception e){
324 <            fail("Unexpected exception");
285 <        }
299 >        final CountDownLatch pleaseTake = new CountDownLatch(1);
300 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
301 >        Thread t = newStartedThread(new CheckedRunnable() {
302 >            public void realRun() throws InterruptedException {
303 >                for (int i = 0; i < capacity; i++)
304 >                    q.put(i);
305 >                pleaseTake.countDown();
306 >                q.put(86);
307 >
308 >                pleaseInterrupt.countDown();
309 >                try {
310 >                    q.put(99);
311 >                    shouldThrow();
312 >                } catch (InterruptedException success) {}
313 >                assertFalse(Thread.interrupted());
314 >            }});
315 >
316 >        await(pleaseTake);
317 >        assertEquals(0, q.remainingCapacity());
318 >        assertEquals(0, q.take());
319 >
320 >        await(pleaseInterrupt);
321 >        assertThreadStaysAlive(t);
322 >        t.interrupt();
323 >        awaitTermination(t);
324 >        assertEquals(0, q.remainingCapacity());
325      }
326  
327 +    /**
328 +     * timed offer times out if full and elements not taken
329 +     */
330      public void testTimedOffer() {
331          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
332 <        Thread t = new Thread(new Runnable() {
333 <                public void run(){
334 <                    try {
335 <                        q.put(new Object());
336 <                        q.put(new Object());
337 <                        assertFalse(q.offer(new Object(), SHORT_DELAY_MS/2, TimeUnit.MILLISECONDS));
338 <                        q.offer(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
339 <                        fail("Should block");
340 <                    } catch (InterruptedException success){}
341 <                }
342 <            });
343 <        
344 <        try {
345 <            t.start();
346 <            Thread.sleep(SHORT_DELAY_MS);
347 <            t.interrupt();
348 <            t.join();
349 <        } catch (Exception e){
350 <            fail("Unexpected exception");
309 <        }
332 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
333 >        Thread t = newStartedThread(new CheckedRunnable() {
334 >            public void realRun() throws InterruptedException {
335 >                q.put(new Object());
336 >                q.put(new Object());
337 >                long startTime = System.nanoTime();
338 >                assertFalse(q.offer(new Object(), timeoutMillis(), MILLISECONDS));
339 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
340 >                pleaseInterrupt.countDown();
341 >                try {
342 >                    q.offer(new Object(), 2 * LONG_DELAY_MS, MILLISECONDS);
343 >                    shouldThrow();
344 >                } catch (InterruptedException success) {}
345 >            }});
346 >
347 >        await(pleaseInterrupt);
348 >        assertThreadStaysAlive(t);
349 >        t.interrupt();
350 >        awaitTermination(t);
351      }
352  
353 <    public void testTake(){
354 <        try {
355 <            LinkedBlockingQueue q = fullQueue(N);
356 <            for (int i = 0; i < N; ++i) {
357 <                assertEquals(i, ((Integer)q.take()).intValue());
358 <            }
359 <        } catch (InterruptedException e){
360 <            fail("Unexpected exception");
320 <        }  
353 >    /**
354 >     * take retrieves elements in FIFO order
355 >     */
356 >    public void testTake() throws InterruptedException {
357 >        LinkedBlockingQueue q = populatedQueue(SIZE);
358 >        for (int i = 0; i < SIZE; ++i) {
359 >            assertEquals(i, q.take());
360 >        }
361      }
362  
363 <    public void testTakeFromEmpty() {
364 <        final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
365 <        Thread t = new Thread(new Runnable() {
366 <                public void run(){
367 <                    try {
368 <                        q.take();
369 <                        fail("Should block");
370 <                    } catch (InterruptedException success){ }                
363 >    /**
364 >     * Take removes existing elements until empty, then blocks interruptibly
365 >     */
366 >    public void testBlockingTake() throws InterruptedException {
367 >        final BlockingQueue q = populatedQueue(SIZE);
368 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
369 >        Thread t = newStartedThread(new CheckedRunnable() {
370 >            public void realRun() throws InterruptedException {
371 >                for (int i = 0; i < SIZE; ++i) {
372 >                    assertEquals(i, q.take());
373                  }
374 <            });
375 <        try {
376 <            t.start();
377 <            Thread.sleep(SHORT_DELAY_MS);
378 <            t.interrupt();
379 <            t.join();
380 <        } catch (Exception e){
381 <            fail("Unexpected exception");
382 <        }
374 >
375 >                Thread.currentThread().interrupt();
376 >                try {
377 >                    q.take();
378 >                    shouldThrow();
379 >                } catch (InterruptedException success) {}
380 >                assertFalse(Thread.interrupted());
381 >
382 >                pleaseInterrupt.countDown();
383 >                try {
384 >                    q.take();
385 >                    shouldThrow();
386 >                } catch (InterruptedException success) {}
387 >                assertFalse(Thread.interrupted());
388 >            }});
389 >
390 >        await(pleaseInterrupt);
391 >        assertThreadStaysAlive(t);
392 >        t.interrupt();
393 >        awaitTermination(t);
394      }
395  
396 <    public void testBlockingTake(){
397 <        Thread t = new Thread(new Runnable() {
398 <                public void run() {
399 <                    try {
400 <                        LinkedBlockingQueue q = fullQueue(N);
401 <                        for (int i = 0; i < N; ++i) {
402 <                            assertEquals(i, ((Integer)q.take()).intValue());
350 <                        }
351 <                        q.take();
352 <                        fail("take should block");
353 <                    } catch (InterruptedException success){
354 <                    }  
355 <                }});
356 <        t.start();
357 <        try {
358 <           Thread.sleep(SHORT_DELAY_MS);
359 <           t.interrupt();
360 <           t.join();
361 <        }
362 <        catch (InterruptedException ie) {
363 <            fail("Unexpected exception");
396 >    /**
397 >     * poll succeeds unless empty
398 >     */
399 >    public void testPoll() {
400 >        LinkedBlockingQueue q = populatedQueue(SIZE);
401 >        for (int i = 0; i < SIZE; ++i) {
402 >            assertEquals(i, q.poll());
403          }
404 +        assertNull(q.poll());
405      }
406  
407 <
408 <    public void testPoll(){
409 <        LinkedBlockingQueue q = fullQueue(N);
410 <        for (int i = 0; i < N; ++i) {
411 <            assertEquals(i, ((Integer)q.poll()).intValue());
407 >    /**
408 >     * timed poll with zero timeout succeeds when non-empty, else times out
409 >     */
410 >    public void testTimedPoll0() throws InterruptedException {
411 >        LinkedBlockingQueue q = populatedQueue(SIZE);
412 >        for (int i = 0; i < SIZE; ++i) {
413 >            assertEquals(i, q.poll(0, MILLISECONDS));
414          }
415 <        assertNull(q.poll());
415 >        assertNull(q.poll(0, MILLISECONDS));
416      }
417  
418 <    public void testTimedPoll0() {
419 <        try {
420 <            LinkedBlockingQueue q = fullQueue(N);
421 <            for (int i = 0; i < N; ++i) {
422 <                assertEquals(i, ((Integer)q.poll(0, TimeUnit.MILLISECONDS)).intValue());
423 <            }
424 <            assertNull(q.poll(0, TimeUnit.MILLISECONDS));
425 <        } catch (InterruptedException e){
426 <            fail("Unexpected exception");
427 <        }  
418 >    /**
419 >     * timed poll with nonzero timeout succeeds when non-empty, else times out
420 >     */
421 >    public void testTimedPoll() throws InterruptedException {
422 >        LinkedBlockingQueue<Integer> q = populatedQueue(SIZE);
423 >        for (int i = 0; i < SIZE; ++i) {
424 >            long startTime = System.nanoTime();
425 >            assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
426 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
427 >        }
428 >        long startTime = System.nanoTime();
429 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
430 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
431 >        checkEmpty(q);
432      }
433  
434 <    public void testTimedPoll() {
435 <        try {
436 <            LinkedBlockingQueue q = fullQueue(N);
437 <            for (int i = 0; i < N; ++i) {
438 <                assertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
439 <            }
440 <            assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
441 <        } catch (InterruptedException e){
442 <            fail("Unexpected exception");
443 <        }  
444 <    }
445 <
446 <    public void testInterruptedTimedPoll(){
447 <        Thread t = new Thread(new Runnable() {
448 <                public void run() {
449 <                    try {
450 <                        LinkedBlockingQueue q = fullQueue(N);
451 <                        for (int i = 0; i < N; ++i) {
452 <                            assertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
453 <                        }
454 <                        assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
455 <                    } catch (InterruptedException success){
456 <                    }  
457 <                }});
458 <        t.start();
459 <        try {
460 <           Thread.sleep(SHORT_DELAY_MS);
461 <           t.interrupt();
462 <           t.join();
417 <        }
418 <        catch (InterruptedException ie) {
419 <            fail("Unexpected exception");
420 <        }
434 >    /**
435 >     * Interrupted timed poll throws InterruptedException instead of
436 >     * returning timeout status
437 >     */
438 >    public void testInterruptedTimedPoll() throws InterruptedException {
439 >        final BlockingQueue<Integer> q = populatedQueue(SIZE);
440 >        final CountDownLatch aboutToWait = new CountDownLatch(1);
441 >        Thread t = newStartedThread(new CheckedRunnable() {
442 >            public void realRun() throws InterruptedException {
443 >                for (int i = 0; i < SIZE; ++i) {
444 >                    long t0 = System.nanoTime();
445 >                    assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
446 >                    assertTrue(millisElapsedSince(t0) < SMALL_DELAY_MS);
447 >                }
448 >                long t0 = System.nanoTime();
449 >                aboutToWait.countDown();
450 >                try {
451 >                    q.poll(MEDIUM_DELAY_MS, MILLISECONDS);
452 >                    shouldThrow();
453 >                } catch (InterruptedException success) {
454 >                    assertTrue(millisElapsedSince(t0) < MEDIUM_DELAY_MS);
455 >                }
456 >            }});
457 >
458 >        aboutToWait.await();
459 >        waitForThreadToEnterWaitState(t, SMALL_DELAY_MS);
460 >        t.interrupt();
461 >        awaitTermination(t, MEDIUM_DELAY_MS);
462 >        checkEmpty(q);
463      }
464  
465 <    public void testTimedPollWithOffer(){
466 <        final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
467 <        Thread t = new Thread(new Runnable() {
468 <                public void run(){
469 <                    try {
470 <                        assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
471 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
472 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
431 <                        fail("Should block");
432 <                    } catch (InterruptedException success) { }                
433 <                }
434 <            });
435 <        try {
436 <            t.start();
437 <            Thread.sleep(SHORT_DELAY_MS * 2);
438 <            assertTrue(q.offer(new Integer(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
439 <            t.interrupt();
440 <            t.join();
441 <        } catch (Exception e){
442 <            fail("Unexpected exception");
443 <        }
444 <    }  
445 <
446 <
447 <    public void testPeek(){
448 <        LinkedBlockingQueue q = fullQueue(N);
449 <        for (int i = 0; i < N; ++i) {
450 <            assertEquals(i, ((Integer)q.peek()).intValue());
451 <            q.poll();
465 >    /**
466 >     * peek returns next element, or null if empty
467 >     */
468 >    public void testPeek() {
469 >        LinkedBlockingQueue q = populatedQueue(SIZE);
470 >        for (int i = 0; i < SIZE; ++i) {
471 >            assertEquals(i, q.peek());
472 >            assertEquals(i, q.poll());
473              assertTrue(q.peek() == null ||
474 <                       i != ((Integer)q.peek()).intValue());
474 >                       !q.peek().equals(i));
475          }
476 <        assertNull(q.peek());
476 >        assertNull(q.peek());
477      }
478  
479 <    public void testElement(){
480 <        LinkedBlockingQueue q = fullQueue(N);
481 <        for (int i = 0; i < N; ++i) {
482 <            assertEquals(i, ((Integer)q.element()).intValue());
483 <            q.poll();
479 >    /**
480 >     * element returns next element, or throws NSEE if empty
481 >     */
482 >    public void testElement() {
483 >        LinkedBlockingQueue q = populatedQueue(SIZE);
484 >        for (int i = 0; i < SIZE; ++i) {
485 >            assertEquals(i, q.element());
486 >            assertEquals(i, q.poll());
487          }
488          try {
489              q.element();
490 <            fail("no such element");
491 <        }
468 <        catch (NoSuchElementException success) {}
490 >            shouldThrow();
491 >        } catch (NoSuchElementException success) {}
492      }
493  
494 <    public void testRemove(){
495 <        LinkedBlockingQueue q = fullQueue(N);
496 <        for (int i = 0; i < N; ++i) {
497 <            assertEquals(i, ((Integer)q.remove()).intValue());
494 >    /**
495 >     * remove removes next element, or throws NSEE if empty
496 >     */
497 >    public void testRemove() {
498 >        LinkedBlockingQueue q = populatedQueue(SIZE);
499 >        for (int i = 0; i < SIZE; ++i) {
500 >            assertEquals(i, q.remove());
501          }
502          try {
503              q.remove();
504 <            fail("remove should throw");
505 <        } catch (NoSuchElementException success){
480 <        }  
504 >            shouldThrow();
505 >        } catch (NoSuchElementException success) {}
506      }
507  
508 <    public void testRemoveElement(){
509 <        LinkedBlockingQueue q = fullQueue(N);
510 <        for (int i = 1; i < N; i+=2) {
511 <            assertTrue(q.remove(new Integer(i)));
512 <        }
513 <        for (int i = 0; i < N; i+=2) {
514 <            assertTrue(q.remove(new Integer(i)));
515 <            assertFalse(q.remove(new Integer(i+1)));
516 <        }
517 <        assertTrue(q.isEmpty());
508 >    /**
509 >     * An add following remove(x) succeeds
510 >     */
511 >    public void testRemoveElementAndAdd() throws InterruptedException {
512 >        LinkedBlockingQueue q = new LinkedBlockingQueue();
513 >        assertTrue(q.add(new Integer(1)));
514 >        assertTrue(q.add(new Integer(2)));
515 >        assertTrue(q.remove(new Integer(1)));
516 >        assertTrue(q.remove(new Integer(2)));
517 >        assertTrue(q.add(new Integer(3)));
518 >        assertNotNull(q.take());
519      }
520 <        
521 <    public void testContains(){
522 <        LinkedBlockingQueue q = fullQueue(N);
523 <        for (int i = 0; i < N; ++i) {
520 >
521 >    /**
522 >     * contains(x) reports true when elements added but not yet removed
523 >     */
524 >    public void testContains() {
525 >        LinkedBlockingQueue q = populatedQueue(SIZE);
526 >        for (int i = 0; i < SIZE; ++i) {
527              assertTrue(q.contains(new Integer(i)));
528              q.poll();
529              assertFalse(q.contains(new Integer(i)));
530          }
531      }
532  
533 <    public void testClear(){
534 <        LinkedBlockingQueue q = fullQueue(N);
533 >    /**
534 >     * clear removes all elements
535 >     */
536 >    public void testClear() {
537 >        LinkedBlockingQueue q = populatedQueue(SIZE);
538          q.clear();
539          assertTrue(q.isEmpty());
540          assertEquals(0, q.size());
541 <        assertEquals(N, q.remainingCapacity());
542 <        q.add(new Integer(1));
541 >        assertEquals(SIZE, q.remainingCapacity());
542 >        q.add(one);
543          assertFalse(q.isEmpty());
544 +        assertTrue(q.contains(one));
545          q.clear();
546          assertTrue(q.isEmpty());
547      }
548  
549 <    public void testContainsAll(){
550 <        LinkedBlockingQueue q = fullQueue(N);
551 <        LinkedBlockingQueue p = new LinkedBlockingQueue(N);
552 <        for (int i = 0; i < N; ++i) {
549 >    /**
550 >     * containsAll(c) is true when c contains a subset of elements
551 >     */
552 >    public void testContainsAll() {
553 >        LinkedBlockingQueue q = populatedQueue(SIZE);
554 >        LinkedBlockingQueue p = new LinkedBlockingQueue(SIZE);
555 >        for (int i = 0; i < SIZE; ++i) {
556              assertTrue(q.containsAll(p));
557              assertFalse(p.containsAll(q));
558              p.add(new Integer(i));
# Line 524 | Line 560 | public class LinkedBlockingQueueTest ext
560          assertTrue(p.containsAll(q));
561      }
562  
563 <    public void testRetainAll(){
564 <        LinkedBlockingQueue q = fullQueue(N);
565 <        LinkedBlockingQueue p = fullQueue(N);
566 <        for (int i = 0; i < N; ++i) {
563 >    /**
564 >     * retainAll(c) retains only those elements of c and reports true if changed
565 >     */
566 >    public void testRetainAll() {
567 >        LinkedBlockingQueue q = populatedQueue(SIZE);
568 >        LinkedBlockingQueue p = populatedQueue(SIZE);
569 >        for (int i = 0; i < SIZE; ++i) {
570              boolean changed = q.retainAll(p);
571              if (i == 0)
572                  assertFalse(changed);
# Line 535 | Line 574 | public class LinkedBlockingQueueTest ext
574                  assertTrue(changed);
575  
576              assertTrue(q.containsAll(p));
577 <            assertEquals(N-i, q.size());
577 >            assertEquals(SIZE-i, q.size());
578              p.remove();
579          }
580      }
581  
582 <    public void testRemoveAll(){
583 <        for (int i = 1; i < N; ++i) {
584 <            LinkedBlockingQueue q = fullQueue(N);
585 <            LinkedBlockingQueue p = fullQueue(i);
582 >    /**
583 >     * removeAll(c) removes only those elements of c and reports true if changed
584 >     */
585 >    public void testRemoveAll() {
586 >        for (int i = 1; i < SIZE; ++i) {
587 >            LinkedBlockingQueue q = populatedQueue(SIZE);
588 >            LinkedBlockingQueue p = populatedQueue(i);
589              assertTrue(q.removeAll(p));
590 <            assertEquals(N-i, q.size());
590 >            assertEquals(SIZE-i, q.size());
591              for (int j = 0; j < i; ++j) {
592 <                Integer I = (Integer)(p.remove());
593 <                assertFalse(q.contains(I));
592 >                Integer x = (Integer)(p.remove());
593 >                assertFalse(q.contains(x));
594              }
595          }
596      }
597  
598 +    /**
599 +     * toArray contains all elements in FIFO order
600 +     */
601 +    public void testToArray() {
602 +        LinkedBlockingQueue q = populatedQueue(SIZE);
603 +        Object[] o = q.toArray();
604 +        for (int i = 0; i < o.length; i++)
605 +            assertSame(o[i], q.poll());
606 +    }
607  
608 <    public void testToArray(){
609 <        LinkedBlockingQueue q = fullQueue(N);
610 <        Object[] o = q.toArray();
611 <        try {
612 <        for(int i = 0; i < o.length; i++)
613 <            assertEquals(o[i], q.take());
614 <        } catch (InterruptedException e){
615 <            fail("Unexpected exception");
616 <        }    
617 <    }
567 <
568 <    public void testToArray2(){
569 <        LinkedBlockingQueue q = fullQueue(N);
570 <        Integer[] ints = new Integer[N];
571 <        ints = (Integer[])q.toArray(ints);
572 <        try {
573 <            for(int i = 0; i < ints.length; i++)
574 <                assertEquals(ints[i], q.take());
575 <        } catch (InterruptedException e){
576 <            fail("Unexpected exception");
577 <        }    
578 <    }
579 <    
580 <    public void testIterator(){
581 <        LinkedBlockingQueue q = fullQueue(N);
582 <        Iterator it = q.iterator();
583 <        try {
584 <            while(it.hasNext()){
585 <                assertEquals(it.next(), q.take());
586 <            }
587 <        } catch (InterruptedException e){
588 <            fail("Unexpected exception");
589 <        }    
608 >    /**
609 >     * toArray(a) contains all elements in FIFO order
610 >     */
611 >    public void testToArray2() throws InterruptedException {
612 >        LinkedBlockingQueue<Integer> q = populatedQueue(SIZE);
613 >        Integer[] ints = new Integer[SIZE];
614 >        Integer[] array = q.toArray(ints);
615 >        assertSame(ints, array);
616 >        for (int i = 0; i < ints.length; i++)
617 >            assertSame(ints[i], q.poll());
618      }
619  
620 <    public void testIteratorOrdering() {
620 >    /**
621 >     * toArray(incompatible array type) throws ArrayStoreException
622 >     */
623 >    public void testToArray1_BadArg() {
624 >        LinkedBlockingQueue q = populatedQueue(SIZE);
625 >        try {
626 >            q.toArray(new String[10]);
627 >            shouldThrow();
628 >        } catch (ArrayStoreException success) {}
629 >    }
630  
631 <        final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
631 >    /**
632 >     * iterator iterates through all elements
633 >     */
634 >    public void testIterator() throws InterruptedException {
635 >        LinkedBlockingQueue q = populatedQueue(SIZE);
636 >        Iterator it = q.iterator();
637 >        int i;
638 >        for (i = 0; it.hasNext(); i++)
639 >            assertTrue(q.contains(it.next()));
640 >        assertEquals(i, SIZE);
641 >        assertIteratorExhausted(it);
642 >
643 >        it = q.iterator();
644 >        for (i = 0; it.hasNext(); i++)
645 >            assertEquals(it.next(), q.take());
646 >        assertEquals(i, SIZE);
647 >        assertIteratorExhausted(it);
648 >    }
649  
650 <        q.add(new Integer(1));
651 <        q.add(new Integer(2));
652 <        q.add(new Integer(3));
650 >    /**
651 >     * iterator of empty collection has no elements
652 >     */
653 >    public void testEmptyIterator() {
654 >        assertIteratorExhausted(new LinkedBlockingQueue().iterator());
655 >    }
656  
657 <        assertEquals("queue should be full", 0, q.remainingCapacity());
657 >    /**
658 >     * iterator.remove removes current element
659 >     */
660 >    public void testIteratorRemove() {
661 >        final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
662 >        q.add(two);
663 >        q.add(one);
664 >        q.add(three);
665 >
666 >        Iterator it = q.iterator();
667 >        it.next();
668 >        it.remove();
669 >
670 >        it = q.iterator();
671 >        assertSame(it.next(), one);
672 >        assertSame(it.next(), three);
673 >        assertFalse(it.hasNext());
674 >    }
675  
676 +    /**
677 +     * iterator ordering is FIFO
678 +     */
679 +    public void testIteratorOrdering() {
680 +        final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
681 +        q.add(one);
682 +        q.add(two);
683 +        q.add(three);
684 +        assertEquals(0, q.remainingCapacity());
685          int k = 0;
686          for (Iterator it = q.iterator(); it.hasNext();) {
687 <            int i = ((Integer)(it.next())).intValue();
605 <            assertEquals("items should come out in order", ++k, i);
687 >            assertEquals(++k, it.next());
688          }
689 <
608 <        assertEquals("should go through 3 elements", 3, k);
689 >        assertEquals(3, k);
690      }
691  
692 <    public void testWeaklyConsistentIteration () {
693 <
692 >    /**
693 >     * Modifications do not cause iterators to fail
694 >     */
695 >    public void testWeaklyConsistentIteration() {
696          final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
697 <
698 <        q.add(new Integer(1));
699 <        q.add(new Integer(2));
700 <        q.add(new Integer(3));
701 <
702 <        try {
620 <            for (Iterator it = q.iterator(); it.hasNext();) {
621 <                q.remove();
622 <                it.next();
623 <            }
624 <        }
625 <        catch (ConcurrentModificationException e) {
626 <            fail("weakly consistent iterator; should not get CME");
697 >        q.add(one);
698 >        q.add(two);
699 >        q.add(three);
700 >        for (Iterator it = q.iterator(); it.hasNext();) {
701 >            q.remove();
702 >            it.next();
703          }
704 <
629 <        assertEquals("queue should be empty again", 0, q.size());
704 >        assertEquals(0, q.size());
705      }
706  
707 <
708 <    public void testToString(){
709 <        LinkedBlockingQueue q = fullQueue(N);
707 >    /**
708 >     * toString contains toStrings of elements
709 >     */
710 >    public void testToString() {
711 >        LinkedBlockingQueue q = populatedQueue(SIZE);
712          String s = q.toString();
713 <        for (int i = 0; i < N; ++i) {
714 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
713 >        for (int i = 0; i < SIZE; ++i) {
714 >            assertTrue(s.contains(String.valueOf(i)));
715          }
716 <    }        
640 <
716 >    }
717  
718 +    /**
719 +     * offer transfers elements across Executor tasks
720 +     */
721      public void testOfferInExecutor() {
643
722          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
723 <
724 <        q.add(new Integer(1));
647 <        q.add(new Integer(2));
648 <
723 >        q.add(one);
724 >        q.add(two);
725          ExecutorService executor = Executors.newFixedThreadPool(2);
726 +        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
727 +        executor.execute(new CheckedRunnable() {
728 +            public void realRun() throws InterruptedException {
729 +                assertFalse(q.offer(three));
730 +                threadsStarted.await();
731 +                assertTrue(q.offer(three, LONG_DELAY_MS, MILLISECONDS));
732 +                assertEquals(0, q.remainingCapacity());
733 +            }});
734 +
735 +        executor.execute(new CheckedRunnable() {
736 +            public void realRun() throws InterruptedException {
737 +                threadsStarted.await();
738 +                assertSame(one, q.take());
739 +            }});
740  
741 <        executor.execute(new Runnable() {
652 <            public void run() {
653 <                assertFalse("offer should be rejected", q.offer(new Integer(3)));
654 <                try {
655 <                    assertTrue("offer should be accepted", q.offer(new Integer(3), MEDIUM_DELAY_MS * 2, TimeUnit.MILLISECONDS));
656 <                    assertEquals(0, q.remainingCapacity());
657 <                }
658 <                catch (InterruptedException e) {
659 <                    fail("should not be interrupted");
660 <                }
661 <            }
662 <        });
663 <
664 <        executor.execute(new Runnable() {
665 <            public void run() {
666 <                try {
667 <                    Thread.sleep(MEDIUM_DELAY_MS);
668 <                    assertEquals("first item in queue should be 1", new Integer(1), q.take());
669 <                }
670 <                catch (InterruptedException e) {
671 <                    fail("should not be interrupted");
672 <                }
673 <            }
674 <        });
675 <        
676 <        executor.shutdown();
677 <
741 >        joinPool(executor);
742      }
743  
744 +    /**
745 +     * timed poll retrieves elements across Executor threads
746 +     */
747      public void testPollInExecutor() {
681
748          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
749 <
749 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
750          ExecutorService executor = Executors.newFixedThreadPool(2);
751 +        executor.execute(new CheckedRunnable() {
752 +            public void realRun() throws InterruptedException {
753 +                assertNull(q.poll());
754 +                threadsStarted.await();
755 +                assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
756 +                checkEmpty(q);
757 +            }});
758 +
759 +        executor.execute(new CheckedRunnable() {
760 +            public void realRun() throws InterruptedException {
761 +                threadsStarted.await();
762 +                q.put(one);
763 +            }});
764  
765 <        executor.execute(new Runnable() {
766 <            public void run() {
688 <                assertNull("poll should fail", q.poll());
689 <                try {
690 <                    assertTrue(null != q.poll(MEDIUM_DELAY_MS * 2, TimeUnit.MILLISECONDS));
691 <                    assertTrue(q.isEmpty());
692 <                }
693 <                catch (InterruptedException e) {
694 <                    fail("should not be interrupted");
695 <                }
696 <            }
697 <        });
765 >        joinPool(executor);
766 >    }
767  
768 <        executor.execute(new Runnable() {
769 <            public void run() {
770 <                try {
771 <                    Thread.sleep(MEDIUM_DELAY_MS);
772 <                    q.put(new Integer(1));
773 <                }
774 <                catch (InterruptedException e) {
775 <                    fail("should not be interrupted");
776 <                }
777 <            }
778 <        });
779 <        
780 <        executor.shutdown();
768 >    /**
769 >     * A deserialized serialized queue has same elements in same order
770 >     */
771 >    public void testSerialization() throws Exception {
772 >        Queue x = populatedQueue(SIZE);
773 >        Queue y = serialClone(x);
774 >
775 >        assertNotSame(x, y);
776 >        assertEquals(x.size(), y.size());
777 >        assertEquals(x.toString(), y.toString());
778 >        assertTrue(Arrays.equals(x.toArray(), y.toArray()));
779 >        while (!x.isEmpty()) {
780 >            assertFalse(y.isEmpty());
781 >            assertEquals(x.remove(), y.remove());
782 >        }
783 >        assertTrue(y.isEmpty());
784 >    }
785 >
786 >    /**
787 >     * drainTo(c) empties queue into another collection c
788 >     */
789 >    public void testDrainTo() {
790 >        LinkedBlockingQueue q = populatedQueue(SIZE);
791 >        ArrayList l = new ArrayList();
792 >        q.drainTo(l);
793 >        assertEquals(0, q.size());
794 >        assertEquals(SIZE, l.size());
795 >        for (int i = 0; i < SIZE; ++i)
796 >            assertEquals(l.get(i), new Integer(i));
797 >        q.add(zero);
798 >        q.add(one);
799 >        assertFalse(q.isEmpty());
800 >        assertTrue(q.contains(zero));
801 >        assertTrue(q.contains(one));
802 >        l.clear();
803 >        q.drainTo(l);
804 >        assertEquals(0, q.size());
805 >        assertEquals(2, l.size());
806 >        for (int i = 0; i < 2; ++i)
807 >            assertEquals(l.get(i), new Integer(i));
808 >    }
809  
810 +    /**
811 +     * drainTo empties full queue, unblocking a waiting put.
812 +     */
813 +    public void testDrainToWithActivePut() throws InterruptedException {
814 +        final LinkedBlockingQueue q = populatedQueue(SIZE);
815 +        Thread t = new Thread(new CheckedRunnable() {
816 +            public void realRun() throws InterruptedException {
817 +                q.put(new Integer(SIZE+1));
818 +            }});
819 +
820 +        t.start();
821 +        ArrayList l = new ArrayList();
822 +        q.drainTo(l);
823 +        assertTrue(l.size() >= SIZE);
824 +        for (int i = 0; i < SIZE; ++i)
825 +            assertEquals(l.get(i), new Integer(i));
826 +        t.join();
827 +        assertTrue(q.size() + l.size() >= SIZE);
828      }
829  
830 <    public void testSerialization() {
831 <        LinkedBlockingQueue q = fullQueue(N);
832 <
833 <        try {
834 <            ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
835 <            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
836 <            out.writeObject(q);
837 <            out.close();
838 <
839 <            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
840 <            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
841 <            LinkedBlockingQueue r = (LinkedBlockingQueue)in.readObject();
842 <            assertEquals(q.size(), r.size());
843 <            while (!q.isEmpty())
844 <                assertEquals(q.remove(), r.remove());
845 <        } catch(Exception e){
846 <            e.printStackTrace();
847 <            fail("unexpected exception");
830 >    /**
831 >     * drainTo(c, n) empties first min(n, size) elements of queue into c
832 >     */
833 >    public void testDrainToN() {
834 >        LinkedBlockingQueue q = new LinkedBlockingQueue();
835 >        for (int i = 0; i < SIZE + 2; ++i) {
836 >            for (int j = 0; j < SIZE; j++)
837 >                assertTrue(q.offer(new Integer(j)));
838 >            ArrayList l = new ArrayList();
839 >            q.drainTo(l, i);
840 >            int k = (i < SIZE) ? i : SIZE;
841 >            assertEquals(k, l.size());
842 >            assertEquals(SIZE-k, q.size());
843 >            for (int j = 0; j < k; ++j)
844 >                assertEquals(l.get(j), new Integer(j));
845 >            do {} while (q.poll() != null);
846 >        }
847 >    }
848 >
849 >    /**
850 >     * remove(null), contains(null) always return false
851 >     */
852 >    public void testNeverContainsNull() {
853 >        Collection<?>[] qs = {
854 >            new LinkedBlockingQueue<Object>(),
855 >            populatedQueue(2),
856 >        };
857 >
858 >        for (Collection<?> q : qs) {
859 >            assertFalse(q.contains(null));
860 >            assertFalse(q.remove(null));
861          }
862      }
863  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines