ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/Collection8Test.java
Revision: 1.25
Committed: Tue Nov 15 00:08:25 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.24: +5 -2 lines
Log Message:
add CopyOnWriteArrayList generic Collection tests

File Contents

# Content
1 /*
2 * Written by Doug Lea and Martin Buchholz with assistance from
3 * members of JCP JSR-166 Expert Group and released to the public
4 * domain, as explained at
5 * http://creativecommons.org/publicdomain/zero/1.0/
6 */
7
8 import static java.util.concurrent.TimeUnit.HOURS;
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.Collections;
15 import java.util.Deque;
16 import java.util.HashSet;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.NoSuchElementException;
20 import java.util.Queue;
21 import java.util.Spliterator;
22 import java.util.concurrent.BlockingDeque;
23 import java.util.concurrent.BlockingQueue;
24 import java.util.concurrent.CountDownLatch;
25 import java.util.concurrent.Executors;
26 import java.util.concurrent.ExecutorService;
27 import java.util.concurrent.Future;
28 import java.util.concurrent.ThreadLocalRandom;
29 import java.util.concurrent.atomic.AtomicBoolean;
30 import java.util.concurrent.atomic.AtomicLong;
31 import java.util.concurrent.atomic.AtomicReference;
32 import java.util.function.Consumer;
33 import java.util.function.Predicate;
34
35 import junit.framework.Test;
36
37 /**
38 * Contains tests applicable to all jdk8+ Collection implementations.
39 * An extension of CollectionTest.
40 */
41 public class Collection8Test extends JSR166TestCase {
42 final CollectionImplementation impl;
43
44 /** Tests are parameterized by a Collection implementation. */
45 Collection8Test(CollectionImplementation impl, String methodName) {
46 super(methodName);
47 this.impl = impl;
48 }
49
50 public static Test testSuite(CollectionImplementation impl) {
51 return parameterizedTestSuite(Collection8Test.class,
52 CollectionImplementation.class,
53 impl);
54 }
55
56 Object bomb() {
57 return new Object() {
58 public boolean equals(Object x) { throw new AssertionError(); }
59 public int hashCode() { throw new AssertionError(); }
60 };
61 }
62
63 /** Checks properties of empty collections. */
64 public void testEmptyMeansEmpty() throws Throwable {
65 Collection c = impl.emptyCollection();
66 emptyMeansEmpty(c);
67
68 if (c instanceof java.io.Serializable) {
69 try {
70 emptyMeansEmpty(serialClonePossiblyFailing(c));
71 } catch (java.io.NotSerializableException ex) {
72 // excusable when we have a serializable wrapper around
73 // a non-serializable collection, as can happen with:
74 // Vector.subList() => wrapped AbstractList$RandomAccessSubList
75 if (testImplementationDetails
76 && (! c.getClass().getName().matches(
77 "java.util.Collections.*")))
78 throw ex;
79 }
80 }
81
82 Collection clone = cloneableClone(c);
83 if (clone != null)
84 emptyMeansEmpty(clone);
85 }
86
87 void emptyMeansEmpty(Collection c) throws InterruptedException {
88 assertTrue(c.isEmpty());
89 assertEquals(0, c.size());
90 assertEquals("[]", c.toString());
91 {
92 Object[] a = c.toArray();
93 assertEquals(0, a.length);
94 assertSame(Object[].class, a.getClass());
95 }
96 {
97 Object[] a = new Object[0];
98 assertSame(a, c.toArray(a));
99 }
100 {
101 Integer[] a = new Integer[0];
102 assertSame(a, c.toArray(a));
103 }
104 {
105 Integer[] a = { 1, 2, 3};
106 assertSame(a, c.toArray(a));
107 assertNull(a[0]);
108 assertSame(2, a[1]);
109 assertSame(3, a[2]);
110 }
111 assertIteratorExhausted(c.iterator());
112 Consumer alwaysThrows = e -> { throw new AssertionError(); };
113 c.forEach(alwaysThrows);
114 c.iterator().forEachRemaining(alwaysThrows);
115 c.spliterator().forEachRemaining(alwaysThrows);
116 assertFalse(c.spliterator().tryAdvance(alwaysThrows));
117 if (c.spliterator().hasCharacteristics(Spliterator.SIZED))
118 assertEquals(0, c.spliterator().estimateSize());
119 assertFalse(c.contains(bomb()));
120 assertFalse(c.remove(bomb()));
121 if (c instanceof Queue) {
122 Queue q = (Queue) c;
123 assertNull(q.peek());
124 assertNull(q.poll());
125 }
126 if (c instanceof Deque) {
127 Deque d = (Deque) c;
128 assertNull(d.peekFirst());
129 assertNull(d.peekLast());
130 assertNull(d.pollFirst());
131 assertNull(d.pollLast());
132 assertIteratorExhausted(d.descendingIterator());
133 d.descendingIterator().forEachRemaining(alwaysThrows);
134 assertFalse(d.removeFirstOccurrence(bomb()));
135 assertFalse(d.removeLastOccurrence(bomb()));
136 }
137 if (c instanceof BlockingQueue) {
138 BlockingQueue q = (BlockingQueue) c;
139 assertNull(q.poll(0L, MILLISECONDS));
140 }
141 if (c instanceof BlockingDeque) {
142 BlockingDeque q = (BlockingDeque) c;
143 assertNull(q.pollFirst(0L, MILLISECONDS));
144 assertNull(q.pollLast(0L, MILLISECONDS));
145 }
146 }
147
148 public void testNullPointerExceptions() throws InterruptedException {
149 Collection c = impl.emptyCollection();
150 assertThrows(
151 NullPointerException.class,
152 () -> c.addAll(null),
153 () -> c.containsAll(null),
154 () -> c.retainAll(null),
155 () -> c.removeAll(null),
156 () -> c.removeIf(null),
157 () -> c.forEach(null),
158 () -> c.iterator().forEachRemaining(null),
159 () -> c.spliterator().forEachRemaining(null),
160 () -> c.spliterator().tryAdvance(null),
161 () -> c.toArray(null));
162
163 if (!impl.permitsNulls()) {
164 assertThrows(
165 NullPointerException.class,
166 () -> c.add(null));
167 }
168 if (!impl.permitsNulls() && c instanceof Queue) {
169 Queue q = (Queue) c;
170 assertThrows(
171 NullPointerException.class,
172 () -> q.offer(null));
173 }
174 if (!impl.permitsNulls() && c instanceof Deque) {
175 Deque d = (Deque) c;
176 assertThrows(
177 NullPointerException.class,
178 () -> d.addFirst(null),
179 () -> d.addLast(null),
180 () -> d.offerFirst(null),
181 () -> d.offerLast(null),
182 () -> d.push(null),
183 () -> d.descendingIterator().forEachRemaining(null));
184 }
185 if (c instanceof BlockingQueue) {
186 BlockingQueue q = (BlockingQueue) c;
187 assertThrows(
188 NullPointerException.class,
189 () -> {
190 try { q.offer(null, 1L, HOURS); }
191 catch (InterruptedException ex) {
192 throw new AssertionError(ex);
193 }},
194 () -> {
195 try { q.put(null); }
196 catch (InterruptedException ex) {
197 throw new AssertionError(ex);
198 }});
199 }
200 if (c instanceof BlockingDeque) {
201 BlockingDeque q = (BlockingDeque) c;
202 assertThrows(
203 NullPointerException.class,
204 () -> {
205 try { q.offerFirst(null, 1L, HOURS); }
206 catch (InterruptedException ex) {
207 throw new AssertionError(ex);
208 }},
209 () -> {
210 try { q.offerLast(null, 1L, HOURS); }
211 catch (InterruptedException ex) {
212 throw new AssertionError(ex);
213 }},
214 () -> {
215 try { q.putFirst(null); }
216 catch (InterruptedException ex) {
217 throw new AssertionError(ex);
218 }},
219 () -> {
220 try { q.putLast(null); }
221 catch (InterruptedException ex) {
222 throw new AssertionError(ex);
223 }});
224 }
225 }
226
227 public void testNoSuchElementExceptions() {
228 Collection c = impl.emptyCollection();
229 assertThrows(
230 NoSuchElementException.class,
231 () -> c.iterator().next());
232
233 if (c instanceof Queue) {
234 Queue q = (Queue) c;
235 assertThrows(
236 NoSuchElementException.class,
237 () -> q.element(),
238 () -> q.remove());
239 }
240 if (c instanceof Deque) {
241 Deque d = (Deque) c;
242 assertThrows(
243 NoSuchElementException.class,
244 () -> d.getFirst(),
245 () -> d.getLast(),
246 () -> d.removeFirst(),
247 () -> d.removeLast(),
248 () -> d.pop(),
249 () -> d.descendingIterator().next());
250 }
251 }
252
253 public void testRemoveIf() {
254 Collection c = impl.emptyCollection();
255 boolean ordered =
256 c.spliterator().hasCharacteristics(Spliterator.ORDERED);
257 ThreadLocalRandom rnd = ThreadLocalRandom.current();
258 int n = rnd.nextInt(6);
259 for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
260 AtomicReference threwAt = new AtomicReference(null);
261 List orig = rnd.nextBoolean()
262 ? new ArrayList(c)
263 : Arrays.asList(c.toArray());
264
265 // Merely creating an iterator can change ArrayBlockingQueue behavior
266 Iterator it = rnd.nextBoolean() ? c.iterator() : null;
267
268 ArrayList survivors = new ArrayList();
269 ArrayList accepts = new ArrayList();
270 ArrayList rejects = new ArrayList();
271
272 Predicate randomPredicate = e -> {
273 assertNull(threwAt.get());
274 switch (rnd.nextInt(3)) {
275 case 0: accepts.add(e); return true;
276 case 1: rejects.add(e); return false;
277 case 2: threwAt.set(e); throw new ArithmeticException();
278 default: throw new AssertionError();
279 }
280 };
281 try {
282 try {
283 boolean modified = c.removeIf(randomPredicate);
284 assertNull(threwAt.get());
285 assertEquals(modified, accepts.size() > 0);
286 assertEquals(modified, rejects.size() != n);
287 assertEquals(accepts.size() + rejects.size(), n);
288 if (ordered) {
289 assertEquals(rejects,
290 Arrays.asList(c.toArray()));
291 } else {
292 assertEquals(new HashSet(rejects),
293 new HashSet(Arrays.asList(c.toArray())));
294 }
295 } catch (ArithmeticException ok) {
296 assertNotNull(threwAt.get());
297 assertTrue(c.contains(threwAt.get()));
298 }
299 if (it != null && impl.isConcurrent())
300 // check for weakly consistent iterator
301 while (it.hasNext()) assertTrue(orig.contains(it.next()));
302 switch (rnd.nextInt(4)) {
303 case 0: survivors.addAll(c); break;
304 case 1: survivors.addAll(Arrays.asList(c.toArray())); break;
305 case 2: c.forEach(e -> survivors.add(e)); break;
306 case 3: for (Object e : c) survivors.add(e); break;
307 }
308 assertTrue(orig.containsAll(accepts));
309 assertTrue(orig.containsAll(rejects));
310 assertTrue(orig.containsAll(survivors));
311 assertTrue(orig.containsAll(c));
312 assertTrue(c.containsAll(rejects));
313 assertTrue(c.containsAll(survivors));
314 assertTrue(survivors.containsAll(rejects));
315 if (threwAt.get() == null) {
316 assertEquals(n - accepts.size(), c.size());
317 for (Object x : accepts) assertFalse(c.contains(x));
318 } else {
319 // Two acceptable behaviors: entire removeIf call is one
320 // transaction, or each element processed is one transaction.
321 assertTrue(n == c.size() || n == c.size() + accepts.size());
322 int k = 0;
323 for (Object x : accepts) if (c.contains(x)) k++;
324 assertTrue(k == accepts.size() || k == 0);
325 }
326 } catch (Throwable ex) {
327 System.err.println(impl.klazz());
328 // c is at risk of corruption if we got here, so be lenient
329 try { System.err.printf("c=%s%n", c); }
330 catch (Throwable t) { t.printStackTrace(); }
331 System.err.printf("n=%d%n", n);
332 System.err.printf("orig=%s%n", orig);
333 System.err.printf("accepts=%s%n", accepts);
334 System.err.printf("rejects=%s%n", rejects);
335 System.err.printf("survivors=%s%n", survivors);
336 System.err.printf("threwAt=%s%n", threwAt.get());
337 throw ex;
338 }
339 }
340
341 /**
342 * Various ways of traversing a collection yield same elements
343 */
344 public void testIteratorEquivalence() {
345 Collection c = impl.emptyCollection();
346 ThreadLocalRandom rnd = ThreadLocalRandom.current();
347 int n = rnd.nextInt(6);
348 for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
349 ArrayList iterated = new ArrayList();
350 ArrayList iteratedForEachRemaining = new ArrayList();
351 ArrayList tryAdvanced = new ArrayList();
352 ArrayList spliterated = new ArrayList();
353 ArrayList forEached = new ArrayList();
354 ArrayList removeIfed = new ArrayList();
355 for (Object x : c) iterated.add(x);
356 c.iterator().forEachRemaining(e -> iteratedForEachRemaining.add(e));
357 for (Spliterator s = c.spliterator();
358 s.tryAdvance(e -> tryAdvanced.add(e)); ) {}
359 c.spliterator().forEachRemaining(e -> spliterated.add(e));
360 c.forEach(e -> forEached.add(e));
361 c.removeIf(e -> { removeIfed.add(e); return false; });
362 boolean ordered =
363 c.spliterator().hasCharacteristics(Spliterator.ORDERED);
364 if (c instanceof List || c instanceof Deque)
365 assertTrue(ordered);
366 if (ordered) {
367 assertEquals(iterated, iteratedForEachRemaining);
368 assertEquals(iterated, tryAdvanced);
369 assertEquals(iterated, spliterated);
370 assertEquals(iterated, forEached);
371 assertEquals(iterated, removeIfed);
372 } else {
373 HashSet cset = new HashSet(c);
374 assertEquals(cset, new HashSet(iterated));
375 assertEquals(cset, new HashSet(iteratedForEachRemaining));
376 assertEquals(cset, new HashSet(tryAdvanced));
377 assertEquals(cset, new HashSet(spliterated));
378 assertEquals(cset, new HashSet(forEached));
379 assertEquals(cset, new HashSet(removeIfed));
380 }
381 if (c instanceof Deque) {
382 Deque d = (Deque) c;
383 ArrayList descending = new ArrayList();
384 ArrayList descendingForEachRemaining = new ArrayList();
385 for (Iterator it = d.descendingIterator(); it.hasNext(); )
386 descending.add(it.next());
387 d.descendingIterator().forEachRemaining(
388 e -> descendingForEachRemaining.add(e));
389 Collections.reverse(descending);
390 Collections.reverse(descendingForEachRemaining);
391 assertEquals(iterated, descending);
392 assertEquals(iterated, descendingForEachRemaining);
393 }
394 }
395
396 /**
397 * Calling Iterator#remove() after Iterator#forEachRemaining
398 * should (maybe) remove last element
399 */
400 public void testRemoveAfterForEachRemaining() {
401 Collection c = impl.emptyCollection();
402 ThreadLocalRandom rnd = ThreadLocalRandom.current();
403 testCollection: {
404 int n = 3 + rnd.nextInt(2);
405 for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
406 Iterator it = c.iterator();
407 assertTrue(it.hasNext());
408 assertEquals(impl.makeElement(0), it.next());
409 assertTrue(it.hasNext());
410 assertEquals(impl.makeElement(1), it.next());
411 it.forEachRemaining(e -> assertTrue(c.contains(e)));
412 if (testImplementationDetails) {
413 if (c instanceof java.util.concurrent.ArrayBlockingQueue) {
414 assertIteratorExhausted(it);
415 } else {
416 try { it.remove(); }
417 catch (UnsupportedOperationException ok) {
418 break testCollection;
419 }
420 assertEquals(n - 1, c.size());
421 for (int i = 0; i < n - 1; i++)
422 assertTrue(c.contains(impl.makeElement(i)));
423 assertFalse(c.contains(impl.makeElement(n - 1)));
424 }
425 }
426 }
427 if (c instanceof Deque) {
428 Deque d = (Deque) impl.emptyCollection();
429 int n = 3 + rnd.nextInt(2);
430 for (int i = 0; i < n; i++) d.add(impl.makeElement(i));
431 Iterator it = d.descendingIterator();
432 assertTrue(it.hasNext());
433 assertEquals(impl.makeElement(n - 1), it.next());
434 assertTrue(it.hasNext());
435 assertEquals(impl.makeElement(n - 2), it.next());
436 it.forEachRemaining(e -> assertTrue(c.contains(e)));
437 if (testImplementationDetails) {
438 it.remove();
439 assertEquals(n - 1, d.size());
440 for (int i = 1; i < n; i++)
441 assertTrue(d.contains(impl.makeElement(i)));
442 assertFalse(d.contains(impl.makeElement(0)));
443 }
444 }
445 }
446
447 /**
448 * stream().forEach returns elements in the collection
449 */
450 public void testStreamForEach() throws Throwable {
451 final Collection c = impl.emptyCollection();
452 final AtomicLong count = new AtomicLong(0L);
453 final Object x = impl.makeElement(1);
454 final Object y = impl.makeElement(2);
455 final ArrayList found = new ArrayList();
456 Consumer<Object> spy = o -> found.add(o);
457 c.stream().forEach(spy);
458 assertTrue(found.isEmpty());
459
460 assertTrue(c.add(x));
461 c.stream().forEach(spy);
462 assertEquals(Collections.singletonList(x), found);
463 found.clear();
464
465 assertTrue(c.add(y));
466 c.stream().forEach(spy);
467 assertEquals(2, found.size());
468 assertTrue(found.contains(x));
469 assertTrue(found.contains(y));
470 found.clear();
471
472 c.clear();
473 c.stream().forEach(spy);
474 assertTrue(found.isEmpty());
475 }
476
477 public void testStreamForEachConcurrentStressTest() throws Throwable {
478 if (!impl.isConcurrent()) return;
479 final Collection c = impl.emptyCollection();
480 final long testDurationMillis = timeoutMillis();
481 final AtomicBoolean done = new AtomicBoolean(false);
482 final Object elt = impl.makeElement(1);
483 final Future<?> f1, f2;
484 final ExecutorService pool = Executors.newCachedThreadPool();
485 try (PoolCleaner cleaner = cleaner(pool, done)) {
486 final CountDownLatch threadsStarted = new CountDownLatch(2);
487 Runnable checkElt = () -> {
488 threadsStarted.countDown();
489 while (!done.get())
490 c.stream().forEach(x -> assertSame(x, elt)); };
491 Runnable addRemove = () -> {
492 threadsStarted.countDown();
493 while (!done.get()) {
494 assertTrue(c.add(elt));
495 assertTrue(c.remove(elt));
496 }};
497 f1 = pool.submit(checkElt);
498 f2 = pool.submit(addRemove);
499 Thread.sleep(testDurationMillis);
500 }
501 assertNull(f1.get(0L, MILLISECONDS));
502 assertNull(f2.get(0L, MILLISECONDS));
503 }
504
505 /**
506 * collection.forEach returns elements in the collection
507 */
508 public void testForEach() throws Throwable {
509 final Collection c = impl.emptyCollection();
510 final AtomicLong count = new AtomicLong(0L);
511 final Object x = impl.makeElement(1);
512 final Object y = impl.makeElement(2);
513 final ArrayList found = new ArrayList();
514 Consumer<Object> spy = o -> found.add(o);
515 c.forEach(spy);
516 assertTrue(found.isEmpty());
517
518 assertTrue(c.add(x));
519 c.forEach(spy);
520 assertEquals(Collections.singletonList(x), found);
521 found.clear();
522
523 assertTrue(c.add(y));
524 c.forEach(spy);
525 assertEquals(2, found.size());
526 assertTrue(found.contains(x));
527 assertTrue(found.contains(y));
528 found.clear();
529
530 c.clear();
531 c.forEach(spy);
532 assertTrue(found.isEmpty());
533 }
534
535 public void testForEachConcurrentStressTest() throws Throwable {
536 if (!impl.isConcurrent()) return;
537 final Collection c = impl.emptyCollection();
538 final long testDurationMillis = timeoutMillis();
539 final AtomicBoolean done = new AtomicBoolean(false);
540 final Object elt = impl.makeElement(1);
541 final Future<?> f1, f2;
542 final ExecutorService pool = Executors.newCachedThreadPool();
543 try (PoolCleaner cleaner = cleaner(pool, done)) {
544 final CountDownLatch threadsStarted = new CountDownLatch(2);
545 Runnable checkElt = () -> {
546 threadsStarted.countDown();
547 while (!done.get())
548 c.forEach(x -> assertSame(x, elt)); };
549 Runnable addRemove = () -> {
550 threadsStarted.countDown();
551 while (!done.get()) {
552 assertTrue(c.add(elt));
553 assertTrue(c.remove(elt));
554 }};
555 f1 = pool.submit(checkElt);
556 f2 = pool.submit(addRemove);
557 Thread.sleep(testDurationMillis);
558 }
559 assertNull(f1.get(0L, MILLISECONDS));
560 assertNull(f2.get(0L, MILLISECONDS));
561 }
562
563 // public void testCollection8DebugFail() {
564 // fail(impl.klazz().getSimpleName());
565 // }
566 }