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.1 by dl, Sun Aug 31 19:24:55 2003 UTC vs.
Revision 1.84 by jsr166, Thu Sep 5 21:11:13 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 <
13 < public class PriorityBlockingQueueTest extends TestCase {
14 <
15 <    private static final int N = 10;
16 <    private static final long SHORT_DELAY_MS = 100;
17 <    private static final long MEDIUM_DELAY_MS = 1000;
18 <    private static final long LONG_DELAY_MS = 10000;
19 <    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();
31 <            int j = ((Integer)y).intValue();
32 <            if (i < j) return 1;
33 <            if (i > j) return -1;
34 <            return 0;
80 >            return ((Comparable)y).compareTo(x);
81          }
82      }
83  
38
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 <        }
65 <        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 <        }
74 <        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");
82 <        }
83 <        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);
151 <            q.offer(null);
152 <            fail("should throw NPE");
153 <        } catch (NullPointerException success) { }  
154 <    }
155 <
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 {
164            PriorityBlockingQueue q = new PriorityBlockingQueue(1);
165            q.offer(new Object());
166            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          }
170        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");
186 <        }
187 <        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 {
191            PriorityBlockingQueue q = new PriorityBlockingQueue(N);
192            Integer[] ints = new Integer[N];
271              q.addAll(Arrays.asList(ints));
272 <            fail("Cannot add null elements");
273 <        }
196 <        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)));
219 <            for (int i = 0; i < N; ++i)
220 <                assertEquals(ints[i], q.poll());
221 <        }
222 <        finally {}
223 <    }
224 <
225 <     public void testPutNull() {
226 <        try {
227 <            PriorityBlockingQueue q = new PriorityBlockingQueue(N);
228 <            q.put(null);
229 <            fail("put should throw NPE");
230 <        }
231 <        catch (NullPointerException success){
232 <        }  
233 <     }
234 <
235 <     public void testPut() {
236 <         try {
237 <             PriorityBlockingQueue q = new PriorityBlockingQueue(N);
238 <             for (int i = 0; i < N; ++i) {
239 <                 Integer I = new Integer(i);
240 <                 q.put(I);
241 <                 assertTrue(q.contains(I));
242 <             }
243 <             assertEquals(N, q.size());
244 <         }
245 <         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;
261 <                        q.put(new Integer(0));
262 <                        ++added;
263 <                        assertTrue(added == 4);
264 <                    } finally {
265 <                    }
266 <                }
267 <            });
268 <        try {
269 <            t.start();
270 <            Thread.sleep(SHORT_DELAY_MS);
271 <            q.take();
272 <            t.interrupt();
273 <            t.join();
274 <        } catch (Exception e){
275 <            fail("Unexpected exception");
276 <        }
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 +     * Queue is unbounded, so timed offer never times 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));
288 <                    } finally { }
289 <                }
290 <            });
291 <        
292 <        try {
293 <            t.start();
294 <            Thread.sleep(SHORT_DELAY_MS);
295 <            t.interrupt();
296 <            t.join();
297 <        } catch (Exception e){
298 <            fail("Unexpected exception");
299 <        }
300 <    }
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(){
303 <        try {
304 <            PriorityBlockingQueue q = fullQueue(N);
305 <            for (int i = 0; i < N; ++i) {
306 <                assertEquals(i, ((Integer)q.take()).intValue());
307 <            }
308 <        } catch (InterruptedException e){
309 <            fail("Unexpected exception");
310 <        }  
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");
320 <                    } catch (InterruptedException success){ }                
321 <                }
322 <            });
323 <        try {
324 <            t.start();
325 <            Thread.sleep(SHORT_DELAY_MS);
326 <            t.interrupt();
327 <            t.join();
328 <        } catch (Exception e){
329 <            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();
342 <                        fail("take should block");
343 <                    } catch (InterruptedException success){
344 <                    }  
345 <                }});
346 <        t.start();
347 <        try {
348 <           Thread.sleep(SHORT_DELAY_MS);
349 <           t.interrupt();
350 <           t.join();
351 <        }
352 <        catch (InterruptedException ie) {
353 <            fail("Unexpected exception");
354 <        }
355 <    }
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");
375 <        }  
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));
385 <        } catch (InterruptedException e){
386 <            fail("Unexpected exception");
387 <        }  
388 <    }
389 <
390 <    public void testInterruptedTimedPoll(){
391 <        Thread t = new Thread(new Runnable() {
392 <                public void run() {
393 <                    try {
394 <                        PriorityBlockingQueue q = fullQueue(N);
395 <                        for (int i = 0; i < N; ++i) {
396 <                            assertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
397 <                        }
398 <                        assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
399 <                    } catch (InterruptedException success){
400 <                    }  
401 <                }});
402 <        t.start();
403 <        try {
404 <           Thread.sleep(SHORT_DELAY_MS);
405 <           t.interrupt();
406 <           t.join();
407 <        }
408 <        catch (InterruptedException ie) {
409 <            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);
415 <            assertTrue(q.offer(new Integer(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
416 <            t.interrupt();
417 <            t.join();
418 <        } catch (Exception e){
419 <            fail("Unexpected exception");
420 <        }
421 <    }  
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 >                for (int i = 0; i < SIZE; i++)
426 >                    assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
427  
428 +                Thread.currentThread().interrupt();
429 +                try {
430 +                    q.poll(randomTimeout(), randomTimeUnit());
431 +                    shouldThrow();
432 +                } catch (InterruptedException success) {}
433 +                assertFalse(Thread.interrupted());
434  
435 <    public void testPeek(){
436 <        PriorityBlockingQueue q = fullQueue(N);
437 <        for (int i = 0; i < N; ++i) {
438 <            assertEquals(i, ((Integer)q.peek()).intValue());
439 <            q.poll();
435 >                pleaseInterrupt.countDown();
436 >                try {
437 >                    q.poll(LONGER_DELAY_MS, MILLISECONDS);
438 >                    shouldThrow();
439 >                } catch (InterruptedException success) {}
440 >                assertFalse(Thread.interrupted());
441 >            }});
442 >
443 >        await(pleaseInterrupt);
444 >        if (randomBoolean()) assertThreadBlocks(t, Thread.State.TIMED_WAITING);
445 >        t.interrupt();
446 >        awaitTermination(t);
447 >    }
448 >
449 >    /**
450 >     * peek returns next element, or null if empty
451 >     */
452 >    public void testPeek() {
453 >        PriorityBlockingQueue q = populatedQueue(SIZE);
454 >        for (int i = 0; i < SIZE; ++i) {
455 >            assertEquals(i, q.peek());
456 >            assertEquals(i, q.poll());
457              assertTrue(q.peek() == null ||
458 <                       i != ((Integer)q.peek()).intValue());
458 >                       !q.peek().equals(i));
459          }
460 <        assertNull(q.peek());
460 >        assertNull(q.peek());
461      }
462  
463 <    public void testElement(){
464 <        PriorityBlockingQueue q = fullQueue(N);
465 <        for (int i = 0; i < N; ++i) {
466 <            assertEquals(i, ((Integer)q.element()).intValue());
467 <            q.poll();
463 >    /**
464 >     * element returns next element, or throws NSEE if empty
465 >     */
466 >    public void testElement() {
467 >        PriorityBlockingQueue q = populatedQueue(SIZE);
468 >        for (int i = 0; i < SIZE; ++i) {
469 >            assertEquals(i, q.element());
470 >            assertEquals(i, q.poll());
471          }
472          try {
473              q.element();
474 <            fail("no such element");
475 <        }
458 <        catch (NoSuchElementException success) {}
474 >            shouldThrow();
475 >        } catch (NoSuchElementException success) {}
476      }
477  
478 <    public void testRemove(){
479 <        PriorityBlockingQueue q = fullQueue(N);
480 <        for (int i = 0; i < N; ++i) {
481 <            assertEquals(i, ((Integer)q.remove()).intValue());
478 >    /**
479 >     * remove removes next element, or throws NSEE if empty
480 >     */
481 >    public void testRemove() {
482 >        PriorityBlockingQueue q = populatedQueue(SIZE);
483 >        for (int i = 0; i < SIZE; ++i) {
484 >            assertEquals(i, q.remove());
485          }
486          try {
487              q.remove();
488 <            fail("remove should throw");
489 <        } catch (NoSuchElementException success){
490 <        }  
491 <    }
492 <
493 <    public void testRemoveElement(){
494 <        PriorityBlockingQueue q = fullQueue(N);
495 <        for (int i = 1; i < N; i+=2) {
496 <            assertTrue(q.remove(new Integer(i)));
497 <        }
478 <        for (int i = 0; i < N; i+=2) {
479 <            assertTrue(q.remove(new Integer(i)));
480 <            assertFalse(q.remove(new Integer(i+1)));
481 <        }
482 <        assert(q.isEmpty());
483 <    }
484 <        
485 <    public void testContains(){
486 <        PriorityBlockingQueue q = fullQueue(N);
487 <        for (int i = 0; i < N; ++i) {
488 >            shouldThrow();
489 >        } catch (NoSuchElementException success) {}
490 >    }
491 >
492 >    /**
493 >     * contains(x) reports true when elements added but not yet removed
494 >     */
495 >    public void testContains() {
496 >        PriorityBlockingQueue q = populatedQueue(SIZE);
497 >        for (int i = 0; i < SIZE; ++i) {
498              assertTrue(q.contains(new Integer(i)));
499              q.poll();
500              assertFalse(q.contains(new Integer(i)));
501          }
502      }
503  
504 <    public void testClear(){
505 <        PriorityBlockingQueue q = fullQueue(N);
504 >    /**
505 >     * clear removes all elements
506 >     */
507 >    public void testClear() {
508 >        PriorityBlockingQueue q = populatedQueue(SIZE);
509          q.clear();
510          assertTrue(q.isEmpty());
511          assertEquals(0, q.size());
512 <        assertEquals(NOCAP, q.remainingCapacity());
500 <        q.add(new Integer(1));
512 >        q.add(one);
513          assertFalse(q.isEmpty());
514 +        assertTrue(q.contains(one));
515          q.clear();
516          assertTrue(q.isEmpty());
517      }
518  
519 <    public void testContainsAll(){
520 <        PriorityBlockingQueue q = fullQueue(N);
521 <        PriorityBlockingQueue p = new PriorityBlockingQueue(N);
522 <        for (int i = 0; i < N; ++i) {
519 >    /**
520 >     * containsAll(c) is true when c contains a subset of elements
521 >     */
522 >    public void testContainsAll() {
523 >        PriorityBlockingQueue q = populatedQueue(SIZE);
524 >        PriorityBlockingQueue p = new PriorityBlockingQueue(SIZE);
525 >        for (int i = 0; i < SIZE; ++i) {
526              assertTrue(q.containsAll(p));
527              assertFalse(p.containsAll(q));
528              p.add(new Integer(i));
# Line 514 | Line 530 | public class PriorityBlockingQueueTest e
530          assertTrue(p.containsAll(q));
531      }
532  
533 <    public void testRetainAll(){
534 <        PriorityBlockingQueue q = fullQueue(N);
535 <        PriorityBlockingQueue p = fullQueue(N);
536 <        for (int i = 0; i < N; ++i) {
533 >    /**
534 >     * retainAll(c) retains only those elements of c and reports true if changed
535 >     */
536 >    public void testRetainAll() {
537 >        PriorityBlockingQueue q = populatedQueue(SIZE);
538 >        PriorityBlockingQueue p = populatedQueue(SIZE);
539 >        for (int i = 0; i < SIZE; ++i) {
540              boolean changed = q.retainAll(p);
541              if (i == 0)
542                  assertFalse(changed);
# Line 525 | Line 544 | public class PriorityBlockingQueueTest e
544                  assertTrue(changed);
545  
546              assertTrue(q.containsAll(p));
547 <            assertEquals(N-i, q.size());
547 >            assertEquals(SIZE - i, q.size());
548              p.remove();
549          }
550      }
551  
552 <    public void testRemoveAll(){
553 <        for (int i = 1; i < N; ++i) {
554 <            PriorityBlockingQueue q = fullQueue(N);
555 <            PriorityBlockingQueue p = fullQueue(i);
552 >    /**
553 >     * removeAll(c) removes only those elements of c and reports true if changed
554 >     */
555 >    public void testRemoveAll() {
556 >        for (int i = 1; i < SIZE; ++i) {
557 >            PriorityBlockingQueue q = populatedQueue(SIZE);
558 >            PriorityBlockingQueue p = populatedQueue(i);
559              assertTrue(q.removeAll(p));
560 <            assertEquals(N-i, q.size());
560 >            assertEquals(SIZE - i, q.size());
561              for (int j = 0; j < i; ++j) {
562 <                Integer I = (Integer)(p.remove());
563 <                assertFalse(q.contains(I));
562 >                Integer x = (Integer)(p.remove());
563 >                assertFalse(q.contains(x));
564              }
565          }
566      }
567  
568 <    public void testToArray(){
569 <        PriorityBlockingQueue q = fullQueue(N);
570 <        Object[] o = q.toArray();
571 <        Arrays.sort(o);
572 <        try {
573 <        for(int i = 0; i < o.length; i++)
574 <            assertEquals(o[i], q.take());
575 <        } catch (InterruptedException e){
576 <            fail("Unexpected exception");
577 <        }    
578 <    }
579 <
580 <    public void testToArray2(){
581 <        PriorityBlockingQueue q = fullQueue(N);
582 <        Integer[] ints = new Integer[N];
583 <        ints = (Integer[])q.toArray(ints);
568 >    /**
569 >     * toArray contains all elements
570 >     */
571 >    public void testToArray() throws InterruptedException {
572 >        PriorityBlockingQueue q = populatedQueue(SIZE);
573 >        Object[] a = q.toArray();
574 >        assertSame(Object[].class, a.getClass());
575 >        Arrays.sort(a);
576 >        for (Object o : a)
577 >            assertSame(o, q.take());
578 >        assertTrue(q.isEmpty());
579 >    }
580 >
581 >    /**
582 >     * toArray(a) contains all elements
583 >     */
584 >    public void testToArray2() throws InterruptedException {
585 >        PriorityBlockingQueue<Integer> q = populatedQueue(SIZE);
586 >        Integer[] ints = new Integer[SIZE];
587 >        Integer[] array = q.toArray(ints);
588 >        assertSame(ints, array);
589          Arrays.sort(ints);
590 <        try {
591 <            for(int i = 0; i < ints.length; i++)
592 <                assertEquals(ints[i], q.take());
593 <        } catch (InterruptedException e){
594 <            fail("Unexpected exception");
595 <        }    
596 <    }
597 <    
598 <    public void testIterator(){
599 <        PriorityBlockingQueue q = fullQueue(N);
600 <        int i = 0;
601 <        Iterator it = q.iterator();
602 <        while(it.hasNext()) {
590 >        for (Integer o : ints)
591 >            assertSame(o, q.take());
592 >        assertTrue(q.isEmpty());
593 >    }
594 >
595 >    /**
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 >        Iterator it = q.iterator();
612 >        int i;
613 >        for (i = 0; it.hasNext(); i++)
614              assertTrue(q.contains(it.next()));
615 <            ++i;
616 <        }
579 <        assertEquals(i, N);
615 >        assertEquals(i, SIZE);
616 >        assertIteratorExhausted(it);
617      }
618  
619 <    public void testIteratorRemove () {
619 >    /**
620 >     * iterator of empty collection has no elements
621 >     */
622 >    public void testEmptyIterator() {
623 >        assertIteratorExhausted(new PriorityBlockingQueue().iterator());
624 >    }
625  
626 +    /**
627 +     * iterator.remove removes current element
628 +     */
629 +    public void testIteratorRemove() {
630          final PriorityBlockingQueue q = new PriorityBlockingQueue(3);
585
631          q.add(new Integer(2));
632          q.add(new Integer(1));
633          q.add(new Integer(3));
# Line 597 | Line 642 | public class PriorityBlockingQueueTest e
642          assertFalse(it.hasNext());
643      }
644  
645 <
646 <    public void testToString(){
647 <        PriorityBlockingQueue q = fullQueue(N);
645 >    /**
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 < N; ++i) {
652 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
651 >        for (int i = 0; i < SIZE; ++i) {
652 >            assertTrue(s.contains(String.valueOf(i)));
653          }
654 <    }        
654 >    }
655  
656 +    /**
657 +     * timed poll transfers elements across Executor tasks
658 +     */
659      public void testPollInExecutor() {
610
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);
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 <                assertNull("poll should fail", q.poll());
683 <                try {
684 <                    assertTrue(null != q.poll(MEDIUM_DELAY_MS * 2, TimeUnit.MILLISECONDS));
685 <                    assertTrue(q.isEmpty());
686 <                }
687 <                catch (InterruptedException e) {
688 <                    fail("should not be interrupted");
689 <                }
690 <            }
691 <        });
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 <        executor.execute(new Runnable() {
697 <            public void run() {
698 <                try {
699 <                    Thread.sleep(MEDIUM_DELAY_MS);
700 <                    q.put(new Integer(1));
701 <                }
702 <                catch (InterruptedException e) {
703 <                    fail("should not be interrupted");
704 <                }
705 <            }
706 <        });
707 <        
708 <        executor.shutdown();
696 >    /**
697 >     * drainTo(c) empties queue into another collection c
698 >     */
699 >    public void testDrainTo() {
700 >        PriorityBlockingQueue q = populatedQueue(SIZE);
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  
774   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines