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

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines