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.2 by dl, Sun Sep 7 20:39:11 2003 UTC vs.
Revision 1.82 by jsr166, Sun Aug 11 22:29:27 2019 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 PriorityBlockingQueueTest extends TestCase {
15 <
16 <    private static final int N = 10;
17 <    private static final long SHORT_DELAY_MS = 100;
18 <    private static final long MEDIUM_DELAY_MS = 1000;
19 <    private static final long LONG_DELAY_MS = 10000;
20 <    private static final int NOCAP = Integer.MAX_VALUE;
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  
77 <    static class MyReverseComparator implements Comparator {
77 >    /** Sample Comparator */
78 >    static class MyReverseComparator implements Comparator, java.io.Serializable {
79          public int compare(Object x, Object y) {
80 <            int i = ((Integer)x).intValue();
32 <            int j = ((Integer)y).intValue();
33 <            if (i < j) return 1;
34 <            if (i > j) return -1;
35 <            return 0;
80 >            return ((Comparable)y).compareTo(x);
81          }
82      }
83  
39
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 fullQueue(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 <
103 <    public void testConstructor1(){
104 <        assertEquals(NOCAP, new PriorityBlockingQueue(N).remainingCapacity());
102 >
103 >    /**
104 >     * A new queue has unbounded capacity
105 >     */
106 >    public void testConstructor1() {
107 >        assertEquals(Integer.MAX_VALUE,
108 >                     new PriorityBlockingQueue(SIZE).remainingCapacity());
109      }
110  
111 <    public void testConstructor2(){
111 >    /**
112 >     * Constructor throws IllegalArgumentException if capacity argument nonpositive
113 >     */
114 >    public void testConstructor2() {
115          try {
116 <            PriorityBlockingQueue q = new PriorityBlockingQueue(0);
117 <            fail("Cannot make zero-sized");
118 <        }
66 <        catch (IllegalArgumentException success) {}
116 >            new PriorityBlockingQueue(0);
117 >            shouldThrow();
118 >        } catch (IllegalArgumentException success) {}
119      }
120  
121 <    public void testConstructor3(){
122 <
121 >    /**
122 >     * Initializing from null Collection throws NPE
123 >     */
124 >    public void testConstructor3() {
125          try {
126 <            PriorityBlockingQueue q = new PriorityBlockingQueue(null);
127 <            fail("Cannot make from null collection");
128 <        }
75 <        catch (NullPointerException success) {}
126 >            new PriorityBlockingQueue(null);
127 >            shouldThrow();
128 >        } catch (NullPointerException success) {}
129      }
130  
131 <    public void testConstructor4(){
131 >    /**
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[N];
138 <            PriorityBlockingQueue q = new PriorityBlockingQueue(Arrays.asList(ints));
139 <            fail("Cannot make with null elements");
83 <        }
84 <        catch (NullPointerException success) {}
137 >            new PriorityBlockingQueue(elements);
138 >            shouldThrow();
139 >        } catch (NullPointerException success) {}
140      }
141  
142 <    public void testConstructor5(){
143 <        try {
144 <            Integer[] ints = new Integer[N];
145 <            for (int i = 0; i < N-1; ++i)
146 <                ints[i] = new Integer(i);
147 <            PriorityBlockingQueue q = new PriorityBlockingQueue(Arrays.asList(ints));
148 <            fail("Cannot make with null elements");
149 <        }
150 <        catch (NullPointerException success) {}
142 >    /**
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 >            new PriorityBlockingQueue(elements);
152 >            shouldThrow();
153 >        } catch (NullPointerException success) {}
154      }
155  
156 <    public void testConstructor6(){
157 <        try {
158 <            Integer[] ints = new Integer[N];
159 <            for (int i = 0; i < N; ++i)
160 <                ints[i] = new Integer(i);
161 <            PriorityBlockingQueue q = new PriorityBlockingQueue(Arrays.asList(ints));
162 <            for (int i = 0; i < N; ++i)
163 <                assertEquals(ints[i], q.poll());
164 <        }
165 <        finally {}
156 >    /**
157 >     * Queue contains all elements of collection used to initialize
158 >     */
159 >    public void testConstructor6() {
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 <    public void testConstructor7(){
169 <        try {
170 <            PriorityBlockingQueue q = new PriorityBlockingQueue(N, new MyReverseComparator());
171 <            Integer[] ints = new Integer[N];
172 <            for (int i = 0; i < N; ++i)
173 <                ints[i] = new Integer(i);
174 <            q.addAll(Arrays.asList(ints));
175 <            for (int i = N-1; i >= 0; --i)
176 <                assertEquals(ints[i], q.poll());
177 <        }
178 <        finally {}
168 >    /**
169 >     * The comparator used in constructor is used
170 >     */
171 >    public void testConstructor7() {
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 +     * 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 <    public void testRemainingCapacity(){
199 <        PriorityBlockingQueue q = fullQueue(N);
200 <        for (int i = 0; i < N; ++i) {
201 <            assertEquals(NOCAP, q.remainingCapacity());
202 <            assertEquals(N-i, q.size());
203 <            q.remove();
198 >    /**
199 >     * remainingCapacity() always returns Integer.MAX_VALUE
200 >     */
201 >    public void testRemainingCapacity() {
202 >        BlockingQueue q = populatedQueue(SIZE);
203 >        for (int i = 0; i < SIZE; ++i) {
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 < N; ++i) {
209 <            assertEquals(NOCAP, q.remainingCapacity());
208 >        for (int i = 0; i < SIZE; ++i) {
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 <    public void testOfferNull(){
216 <        try {
217 <            PriorityBlockingQueue q = new PriorityBlockingQueue(1);
152 <            q.offer(null);
153 <            fail("should throw NPE");
154 <        } catch (NullPointerException success) { }  
155 <    }
156 <
215 >    /**
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 +     * Offer of non-Comparable throws CCE
226 +     */
227      public void testOfferNonComparable() {
228 +        PriorityBlockingQueue q = new PriorityBlockingQueue(1);
229          try {
165            PriorityBlockingQueue q = new PriorityBlockingQueue(1);
166            q.offer(new Object());
167            q.offer(new Object());
230              q.offer(new Object());
231 <            fail("should throw CCE");
231 >            shouldThrow();
232 >        } catch (ClassCastException success) {
233 >            assertTrue(q.isEmpty());
234 >            assertEquals(0, q.size());
235 >            assertNull(q.poll());
236          }
171        catch(ClassCastException success) {}
237      }
238  
239 <    public void testAdd(){
240 <        PriorityBlockingQueue q = new PriorityBlockingQueue(N);
241 <        for (int i = 0; i < N; ++i) {
239 >    /**
240 >     * add of comparable succeeds
241 >     */
242 >    public void testAdd() {
243 >        PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE);
244 >        for (int i = 0; i < SIZE; ++i) {
245              assertEquals(i, q.size());
246              assertTrue(q.add(new Integer(i)));
247          }
248      }
249  
250 <    public void testAddAll1(){
250 >    /**
251 >     * addAll(this) throws IllegalArgumentException
252 >     */
253 >    public void testAddAllSelf() {
254 >        PriorityBlockingQueue q = populatedQueue(SIZE);
255          try {
256 <            PriorityBlockingQueue q = new PriorityBlockingQueue(1);
257 <            q.addAll(null);
258 <            fail("Cannot add null collection");
187 <        }
188 <        catch (NullPointerException success) {}
256 >            q.addAll(q);
257 >            shouldThrow();
258 >        } catch (IllegalArgumentException success) {}
259      }
260 <    public void testAddAll2(){
260 >
261 >    /**
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 {
192            PriorityBlockingQueue q = new PriorityBlockingQueue(N);
193            Integer[] ints = new Integer[N];
271              q.addAll(Arrays.asList(ints));
272 <            fail("Cannot add null elements");
273 <        }
197 <        catch (NullPointerException success) {}
272 >            shouldThrow();
273 >        } catch (NullPointerException success) {}
274      }
275 <    public void testAddAll3(){
276 <        try {
277 <            PriorityBlockingQueue q = new PriorityBlockingQueue(N);
278 <            Integer[] ints = new Integer[N];
279 <            for (int i = 0; i < N-1; ++i)
280 <                ints[i] = new Integer(i);
281 <            q.addAll(Arrays.asList(ints));
282 <            fail("Cannot add null elements");
283 <        }
284 <        catch (NullPointerException success) {}
275 >
276 >    /**
277 >     * Queue contains all elements of successful addAll
278 >     */
279 >    public void testAddAll5() {
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 <    public void testAddAll5(){
292 <        try {
293 <            Integer[] empty = new Integer[0];
294 <            Integer[] ints = new Integer[N];
295 <            for (int i = N-1; i >= 0; --i)
296 <                ints[i] = new Integer(i);
297 <            PriorityBlockingQueue q = new PriorityBlockingQueue(N);
298 <            assertFalse(q.addAll(Arrays.asList(empty)));
299 <            assertTrue(q.addAll(Arrays.asList(ints)));
220 <            for (int i = 0; i < N; ++i)
221 <                assertEquals(ints[i], q.poll());
222 <        }
223 <        finally {}
224 <    }
225 <
226 <     public void testPutNull() {
227 <        try {
228 <            PriorityBlockingQueue q = new PriorityBlockingQueue(N);
229 <            q.put(null);
230 <            fail("put should throw NPE");
231 <        }
232 <        catch (NullPointerException success){
233 <        }  
234 <     }
235 <
236 <     public void testPut() {
237 <         try {
238 <             PriorityBlockingQueue q = new PriorityBlockingQueue(N);
239 <             for (int i = 0; i < N; ++i) {
240 <                 Integer I = new Integer(i);
241 <                 q.put(I);
242 <                 assertTrue(q.contains(I));
243 <             }
244 <             assertEquals(N, q.size());
245 <         }
246 <         finally {
291 >    /**
292 >     * all elements successfully put are contained
293 >     */
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 <    public void testPutWithTake() {
304 >    /**
305 >     * put doesn't block waiting for take
306 >     */
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;
262 <                        q.put(new Integer(0));
263 <                        ++added;
264 <                        assertTrue(added == 4);
265 <                    } finally {
266 <                    }
267 <                }
268 <            });
269 <        try {
270 <            t.start();
271 <            Thread.sleep(SHORT_DELAY_MS);
272 <            q.take();
273 <            t.interrupt();
274 <            t.join();
275 <        } catch (Exception e){
276 <            fail("Unexpected exception");
277 <        }
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 +     * 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 <                        assertTrue(q.offer(new Integer(0), SHORT_DELAY_MS/2, TimeUnit.MILLISECONDS));
332 <                        assertTrue(q.offer(new Integer(0), LONG_DELAY_MS, TimeUnit.MILLISECONDS));
289 <                    } finally { }
290 <                }
291 <            });
292 <        
293 <        try {
294 <            t.start();
295 <            Thread.sleep(SHORT_DELAY_MS);
296 <            t.interrupt();
297 <            t.join();
298 <        } catch (Exception e){
299 <            fail("Unexpected exception");
300 <        }
301 <    }
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 <    public void testTake(){
304 <        try {
305 <            PriorityBlockingQueue q = fullQueue(N);
306 <            for (int i = 0; i < N; ++i) {
307 <                assertEquals(i, ((Integer)q.take()).intValue());
308 <            }
309 <        } catch (InterruptedException e){
310 <            fail("Unexpected exception");
311 <        }  
334 >        awaitTermination(t);
335      }
336  
337 <    public void testTakeFromEmpty() {
338 <        final PriorityBlockingQueue q = new PriorityBlockingQueue(2);
339 <        Thread t = new Thread(new Runnable() {
340 <                public void run(){
341 <                    try {
342 <                        q.take();
343 <                        fail("Should block");
321 <                    } catch (InterruptedException success){ }                
322 <                }
323 <            });
324 <        try {
325 <            t.start();
326 <            Thread.sleep(SHORT_DELAY_MS);
327 <            t.interrupt();
328 <            t.join();
329 <        } catch (Exception e){
330 <            fail("Unexpected exception");
337 >    /**
338 >     * take retrieves elements in priority order
339 >     */
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 <    public void testBlockingTake(){
348 <        Thread t = new Thread(new Runnable() {
349 <                public void run() {
350 <                    try {
351 <                        PriorityBlockingQueue q = fullQueue(N);
352 <                        for (int i = 0; i < N; ++i) {
353 <                            assertEquals(i, ((Integer)q.take()).intValue());
354 <                        }
355 <                        q.take();
343 <                        fail("take should block");
344 <                    } catch (InterruptedException success){
345 <                    }  
346 <                }});
347 <        t.start();
348 <        try {
349 <           Thread.sleep(SHORT_DELAY_MS);
350 <           t.interrupt();
351 <           t.join();
352 <        }
353 <        catch (InterruptedException ie) {
354 <            fail("Unexpected exception");
355 <        }
356 <    }
347 >    /**
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 <    public void testPoll(){
365 <        PriorityBlockingQueue q = fullQueue(N);
366 <        for (int i = 0; i < N; ++i) {
367 <            assertEquals(i, ((Integer)q.poll()).intValue());
368 <        }
369 <        assertNull(q.poll());
364 >                pleaseInterrupt.countDown();
365 >                try {
366 >                    q.take();
367 >                    shouldThrow();
368 >                } catch (InterruptedException success) {}
369 >                assertFalse(Thread.interrupted());
370 >            }});
371 >
372 >        await(pleaseInterrupt);
373 >        if (randomBoolean()) assertThreadBlocks(t, Thread.State.WAITING);
374 >        t.interrupt();
375 >        awaitTermination(t);
376      }
377  
378 <    public void testTimedPoll0() {
379 <        try {
380 <            PriorityBlockingQueue q = fullQueue(N);
381 <            for (int i = 0; i < N; ++i) {
382 <                assertEquals(i, ((Integer)q.poll(0, TimeUnit.MILLISECONDS)).intValue());
383 <            }
384 <            assertNull(q.poll(0, TimeUnit.MILLISECONDS));
385 <        } catch (InterruptedException e){
386 <            fail("Unexpected exception");
376 <        }  
378 >    /**
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, q.poll());
385 >        }
386 >        assertNull(q.poll());
387      }
388  
389 <    public void testTimedPoll() {
390 <        try {
391 <            PriorityBlockingQueue q = fullQueue(N);
392 <            for (int i = 0; i < N; ++i) {
393 <                assertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
394 <            }
395 <            assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
386 <        } catch (InterruptedException e){
387 <            fail("Unexpected exception");
388 <        }  
389 <    }
390 <
391 <    public void testInterruptedTimedPoll(){
392 <        Thread t = new Thread(new Runnable() {
393 <                public void run() {
394 <                    try {
395 <                        PriorityBlockingQueue q = fullQueue(N);
396 <                        for (int i = 0; i < N; ++i) {
397 <                            assertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
398 <                        }
399 <                        assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
400 <                    } catch (InterruptedException success){
401 <                    }  
402 <                }});
403 <        t.start();
404 <        try {
405 <           Thread.sleep(SHORT_DELAY_MS);
406 <           t.interrupt();
407 <           t.join();
408 <        }
409 <        catch (InterruptedException ie) {
410 <            fail("Unexpected exception");
389 >    /**
390 >     * timed poll with zero timeout succeeds when non-empty, else times out
391 >     */
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 <    public void testTimedPollWithOffer(){
401 <        final PriorityBlockingQueue q = new PriorityBlockingQueue(2);
402 <        Thread t = new Thread(new Runnable() {
403 <                public void run(){
404 <                    try {
405 <                        assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
406 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
407 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
408 <                        fail("Should block");
409 <                    } catch (InterruptedException success) { }                
410 <                }
411 <            });
412 <        try {
413 <            t.start();
414 <            Thread.sleep(SHORT_DELAY_MS * 2);
429 <            assertTrue(q.offer(new Integer(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
430 <            t.interrupt();
431 <            t.join();
432 <        } catch (Exception e){
433 <            fail("Unexpected exception");
434 <        }
435 <    }  
400 >    /**
401 >     * timed poll with nonzero timeout succeeds when non-empty, else times out
402 >     */
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 +     * Interrupted timed poll throws InterruptedException instead of
418 +     * returning timeout status
419 +     */
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 <    public void testPeek(){
430 <        PriorityBlockingQueue q = fullQueue(N);
431 <        for (int i = 0; i < N; ++i) {
432 <            assertEquals(i, ((Integer)q.peek()).intValue());
433 <            q.poll();
429 >                Thread.currentThread().interrupt();
430 >                try {
431 >                    q.poll(randomTimeout(), randomTimeUnit());
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 >        if (randomBoolean()) assertThreadBlocks(t, Thread.State.TIMED_WAITING);
448 >        t.interrupt();
449 >        awaitTermination(t);
450 >    }
451 >
452 >    /**
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, 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 <    public void testElement(){
467 <        PriorityBlockingQueue q = fullQueue(N);
468 <        for (int i = 0; i < N; ++i) {
469 <            assertEquals(i, ((Integer)q.element()).intValue());
470 <            q.poll();
466 >    /**
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, q.element());
473 >            assertEquals(i, q.poll());
474          }
475          try {
476              q.element();
477 <            fail("no such element");
478 <        }
459 <        catch (NoSuchElementException success) {}
477 >            shouldThrow();
478 >        } catch (NoSuchElementException success) {}
479      }
480  
481 <    public void testRemove(){
482 <        PriorityBlockingQueue q = fullQueue(N);
483 <        for (int i = 0; i < N; ++i) {
484 <            assertEquals(i, ((Integer)q.remove()).intValue());
481 >    /**
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, q.remove());
488          }
489          try {
490              q.remove();
491 <            fail("remove should throw");
492 <        } catch (NoSuchElementException success){
471 <        }  
491 >            shouldThrow();
492 >        } catch (NoSuchElementException success) {}
493      }
494  
495 <    public void testRemoveElement(){
496 <        PriorityBlockingQueue q = fullQueue(N);
497 <        for (int i = 1; i < N; i+=2) {
498 <            assertTrue(q.remove(new Integer(i)));
499 <        }
500 <        for (int i = 0; i < N; i+=2) {
480 <            assertTrue(q.remove(new Integer(i)));
481 <            assertFalse(q.remove(new Integer(i+1)));
482 <        }
483 <        assertTrue(q.isEmpty());
484 <    }
485 <        
486 <    public void testContains(){
487 <        PriorityBlockingQueue q = fullQueue(N);
488 <        for (int i = 0; i < N; ++i) {
495 >    /**
496 >     * contains(x) reports true when elements added but not yet removed
497 >     */
498 >    public void testContains() {
499 >        PriorityBlockingQueue q = populatedQueue(SIZE);
500 >        for (int i = 0; i < SIZE; ++i) {
501              assertTrue(q.contains(new Integer(i)));
502              q.poll();
503              assertFalse(q.contains(new Integer(i)));
504          }
505      }
506  
507 <    public void testClear(){
508 <        PriorityBlockingQueue q = fullQueue(N);
507 >    /**
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());
501 <        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 <    public void testContainsAll(){
523 <        PriorityBlockingQueue q = fullQueue(N);
524 <        PriorityBlockingQueue p = new PriorityBlockingQueue(N);
525 <        for (int i = 0; i < N; ++i) {
522 >    /**
523 >     * containsAll(c) is true when c contains a subset of elements
524 >     */
525 >    public void testContainsAll() {
526 >        PriorityBlockingQueue q = populatedQueue(SIZE);
527 >        PriorityBlockingQueue p = new PriorityBlockingQueue(SIZE);
528 >        for (int i = 0; i < SIZE; ++i) {
529              assertTrue(q.containsAll(p));
530              assertFalse(p.containsAll(q));
531              p.add(new Integer(i));
# Line 515 | Line 533 | public class PriorityBlockingQueueTest e
533          assertTrue(p.containsAll(q));
534      }
535  
536 <    public void testRetainAll(){
537 <        PriorityBlockingQueue q = fullQueue(N);
538 <        PriorityBlockingQueue p = fullQueue(N);
539 <        for (int i = 0; i < N; ++i) {
536 >    /**
537 >     * retainAll(c) retains only those elements of c and reports true if changed
538 >     */
539 >    public void testRetainAll() {
540 >        PriorityBlockingQueue q = populatedQueue(SIZE);
541 >        PriorityBlockingQueue p = populatedQueue(SIZE);
542 >        for (int i = 0; i < SIZE; ++i) {
543              boolean changed = q.retainAll(p);
544              if (i == 0)
545                  assertFalse(changed);
# Line 526 | Line 547 | public class PriorityBlockingQueueTest e
547                  assertTrue(changed);
548  
549              assertTrue(q.containsAll(p));
550 <            assertEquals(N-i, q.size());
550 >            assertEquals(SIZE - i, q.size());
551              p.remove();
552          }
553      }
554  
555 <    public void testRemoveAll(){
556 <        for (int i = 1; i < N; ++i) {
557 <            PriorityBlockingQueue q = fullQueue(N);
558 <            PriorityBlockingQueue p = fullQueue(i);
555 >    /**
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(N-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 <    public void testToArray(){
572 <        PriorityBlockingQueue q = fullQueue(N);
573 <        Object[] o = q.toArray();
574 <        Arrays.sort(o);
575 <        try {
576 <        for(int i = 0; i < o.length; i++)
577 <            assertEquals(o[i], q.take());
578 <        } catch (InterruptedException e){
579 <            fail("Unexpected exception");
580 <        }    
581 <    }
582 <
583 <    public void testToArray2(){
584 <        PriorityBlockingQueue q = fullQueue(N);
585 <        Integer[] ints = new Integer[N];
586 <        ints = (Integer[])q.toArray(ints);
571 >    /**
572 >     * toArray contains all elements
573 >     */
574 >    public void testToArray() throws InterruptedException {
575 >        PriorityBlockingQueue q = populatedQueue(SIZE);
576 >        Object[] a = q.toArray();
577 >        assertSame(Object[].class, a.getClass());
578 >        Arrays.sort(a);
579 >        for (Object o : a)
580 >            assertSame(o, q.take());
581 >        assertTrue(q.isEmpty());
582 >    }
583 >
584 >    /**
585 >     * toArray(a) contains all elements
586 >     */
587 >    public void testToArray2() throws InterruptedException {
588 >        PriorityBlockingQueue<Integer> q = populatedQueue(SIZE);
589 >        Integer[] ints = new Integer[SIZE];
590 >        Integer[] array = q.toArray(ints);
591 >        assertSame(ints, array);
592          Arrays.sort(ints);
593 <        try {
594 <            for(int i = 0; i < ints.length; i++)
595 <                assertEquals(ints[i], q.take());
596 <        } catch (InterruptedException e){
597 <            fail("Unexpected exception");
598 <        }    
599 <    }
600 <    
601 <    public void testIterator(){
602 <        PriorityBlockingQueue q = fullQueue(N);
603 <        int i = 0;
604 <        Iterator it = q.iterator();
605 <        while(it.hasNext()) {
593 >        for (Integer o : ints)
594 >            assertSame(o, q.take());
595 >        assertTrue(q.isEmpty());
596 >    }
597 >
598 >    /**
599 >     * toArray(incompatible array type) throws ArrayStoreException
600 >     */
601 >    public void testToArray1_BadArg() {
602 >        PriorityBlockingQueue q = populatedQueue(SIZE);
603 >        try {
604 >            q.toArray(new String[10]);
605 >            shouldThrow();
606 >        } catch (ArrayStoreException success) {}
607 >    }
608 >
609 >    /**
610 >     * iterator iterates through all elements
611 >     */
612 >    public void testIterator() {
613 >        PriorityBlockingQueue q = populatedQueue(SIZE);
614 >        Iterator it = q.iterator();
615 >        int i;
616 >        for (i = 0; it.hasNext(); i++)
617              assertTrue(q.contains(it.next()));
618 <            ++i;
619 <        }
580 <        assertEquals(i, N);
618 >        assertEquals(i, SIZE);
619 >        assertIteratorExhausted(it);
620      }
621  
622 <    public void testIteratorRemove () {
622 >    /**
623 >     * iterator of empty collection has no elements
624 >     */
625 >    public void testEmptyIterator() {
626 >        assertIteratorExhausted(new PriorityBlockingQueue().iterator());
627 >    }
628  
629 +    /**
630 +     * iterator.remove removes current element
631 +     */
632 +    public void testIteratorRemove() {
633          final PriorityBlockingQueue q = new PriorityBlockingQueue(3);
586
634          q.add(new Integer(2));
635          q.add(new Integer(1));
636          q.add(new Integer(3));
# Line 598 | Line 645 | public class PriorityBlockingQueueTest e
645          assertFalse(it.hasNext());
646      }
647  
648 <
649 <    public void testToString(){
650 <        PriorityBlockingQueue q = fullQueue(N);
648 >    /**
649 >     * toString contains toStrings of elements
650 >     */
651 >    public void testToString() {
652 >        PriorityBlockingQueue q = populatedQueue(SIZE);
653          String s = q.toString();
654 <        for (int i = 0; i < N; ++i) {
655 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
654 >        for (int i = 0; i < SIZE; ++i) {
655 >            assertTrue(s.contains(String.valueOf(i)));
656          }
657 <    }        
657 >    }
658  
659 +    /**
660 +     * timed poll transfers elements across Executor tasks
661 +     */
662      public void testPollInExecutor() {
611
663          final PriorityBlockingQueue q = new PriorityBlockingQueue(2);
664 +        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
665 +        final ExecutorService executor = Executors.newFixedThreadPool(2);
666 +        try (PoolCleaner cleaner = cleaner(executor)) {
667 +            executor.execute(new CheckedRunnable() {
668 +                public void realRun() throws InterruptedException {
669 +                    assertNull(q.poll());
670 +                    threadsStarted.await();
671 +                    assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
672 +                    checkEmpty(q);
673 +                }});
674  
675 <        ExecutorService executor = Executors.newFixedThreadPool(2);
675 >            executor.execute(new CheckedRunnable() {
676 >                public void realRun() throws InterruptedException {
677 >                    threadsStarted.await();
678 >                    q.put(one);
679 >                }});
680 >        }
681 >    }
682  
683 <        executor.execute(new Runnable() {
684 <            public void run() {
685 <                assertNull("poll should fail", q.poll());
686 <                try {
687 <                    assertTrue(null != q.poll(MEDIUM_DELAY_MS * 2, TimeUnit.MILLISECONDS));
688 <                    assertTrue(q.isEmpty());
689 <                }
690 <                catch (InterruptedException e) {
691 <                    fail("should not be interrupted");
692 <                }
693 <            }
694 <        });
683 >    /**
684 >     * A deserialized/reserialized queue has same elements
685 >     */
686 >    public void testSerialization() throws Exception {
687 >        Queue x = populatedQueue(SIZE);
688 >        Queue y = serialClone(x);
689 >
690 >        assertNotSame(x, y);
691 >        assertEquals(x.size(), y.size());
692 >        while (!x.isEmpty()) {
693 >            assertFalse(y.isEmpty());
694 >            assertEquals(x.remove(), y.remove());
695 >        }
696 >        assertTrue(y.isEmpty());
697 >    }
698  
699 <        executor.execute(new Runnable() {
700 <            public void run() {
701 <                try {
702 <                    Thread.sleep(MEDIUM_DELAY_MS);
703 <                    q.put(new Integer(1));
704 <                }
705 <                catch (InterruptedException e) {
706 <                    fail("should not be interrupted");
707 <                }
708 <            }
709 <        });
710 <        
711 <        executor.shutdown();
699 >    /**
700 >     * drainTo(c) empties queue into another collection c
701 >     */
702 >    public void testDrainTo() {
703 >        PriorityBlockingQueue q = populatedQueue(SIZE);
704 >        ArrayList l = new ArrayList();
705 >        q.drainTo(l);
706 >        assertEquals(0, q.size());
707 >        assertEquals(SIZE, l.size());
708 >        for (int i = 0; i < SIZE; ++i)
709 >            assertEquals(l.get(i), new Integer(i));
710 >        q.add(zero);
711 >        q.add(one);
712 >        assertFalse(q.isEmpty());
713 >        assertTrue(q.contains(zero));
714 >        assertTrue(q.contains(one));
715 >        l.clear();
716 >        q.drainTo(l);
717 >        assertEquals(0, q.size());
718 >        assertEquals(2, l.size());
719 >        for (int i = 0; i < 2; ++i)
720 >            assertEquals(l.get(i), new Integer(i));
721 >    }
722  
723 +    /**
724 +     * drainTo empties queue
725 +     */
726 +    public void testDrainToWithActivePut() throws InterruptedException {
727 +        final PriorityBlockingQueue q = populatedQueue(SIZE);
728 +        Thread t = new Thread(new CheckedRunnable() {
729 +            public void realRun() {
730 +                q.put(new Integer(SIZE + 1));
731 +            }});
732 +
733 +        t.start();
734 +        ArrayList l = new ArrayList();
735 +        q.drainTo(l);
736 +        assertTrue(l.size() >= SIZE);
737 +        for (int i = 0; i < SIZE; ++i)
738 +            assertEquals(l.get(i), new Integer(i));
739 +        t.join();
740 +        assertTrue(q.size() + l.size() >= SIZE);
741      }
742  
743 <    public void testSerialization() {
744 <        PriorityBlockingQueue q = fullQueue(N);
745 <        try {
746 <            ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
747 <            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
748 <            out.writeObject(q);
749 <            out.close();
750 <
751 <            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
752 <            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
753 <            PriorityBlockingQueue r = (PriorityBlockingQueue)in.readObject();
754 <            assertEquals(q.size(), r.size());
755 <            while (!q.isEmpty())
756 <                assertEquals(q.remove(), r.remove());
757 <        } catch(Exception e){
758 <            fail("unexpected exception");
743 >    /**
744 >     * drainTo(c, n) empties first min(n, size) elements of queue into c
745 >     */
746 >    public void testDrainToN() {
747 >        PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE * 2);
748 >        for (int i = 0; i < SIZE + 2; ++i) {
749 >            for (int j = 0; j < SIZE; j++)
750 >                assertTrue(q.offer(new Integer(j)));
751 >            ArrayList l = new ArrayList();
752 >            q.drainTo(l, i);
753 >            int k = (i < SIZE) ? i : SIZE;
754 >            assertEquals(k, l.size());
755 >            assertEquals(SIZE - k, q.size());
756 >            for (int j = 0; j < k; ++j)
757 >                assertEquals(l.get(j), new Integer(j));
758 >            do {} while (q.poll() != null);
759 >        }
760 >    }
761 >
762 >    /**
763 >     * remove(null), contains(null) always return false
764 >     */
765 >    public void testNeverContainsNull() {
766 >        Collection<?>[] qs = {
767 >            new PriorityBlockingQueue<Object>(),
768 >            populatedQueue(2),
769 >        };
770 >
771 >        for (Collection<?> q : qs) {
772 >            assertFalse(q.contains(null));
773 >            assertFalse(q.remove(null));
774          }
775      }
776  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines