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