ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/PriorityBlockingQueueTest.java
Revision: 1.59
Committed: Sat Feb 28 19:59:23 2015 UTC (9 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.58: +11 -13 lines
Log Message:
improve testRemainingCapacity

File Contents

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