ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/Collection8Test.java
Revision: 1.58
Committed: Fri Feb 22 19:27:47 2019 UTC (5 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.57: +6 -30 lines
Log Message:
improve assertThrows tests

File Contents

# User Rev Content
1 jsr166 1.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 jsr166 1.16 import static java.util.concurrent.TimeUnit.HOURS;
9 jsr166 1.1 import static java.util.concurrent.TimeUnit.MILLISECONDS;
10    
11 jsr166 1.51 import java.util.ArrayDeque;
12 jsr166 1.1 import java.util.ArrayList;
13 jsr166 1.18 import java.util.Arrays;
14 jsr166 1.1 import java.util.Collection;
15     import java.util.Collections;
16 jsr166 1.42 import java.util.ConcurrentModificationException;
17 jsr166 1.5 import java.util.Deque;
18     import java.util.HashSet;
19     import java.util.Iterator;
20     import java.util.List;
21     import java.util.NoSuchElementException;
22     import java.util.Queue;
23 jsr166 1.48 import java.util.Set;
24 jsr166 1.5 import java.util.Spliterator;
25 jsr166 1.14 import java.util.concurrent.BlockingDeque;
26     import java.util.concurrent.BlockingQueue;
27 jsr166 1.32 import java.util.concurrent.ConcurrentLinkedQueue;
28 jsr166 1.2 import java.util.concurrent.CountDownLatch;
29 jsr166 1.1 import java.util.concurrent.Executors;
30     import java.util.concurrent.ExecutorService;
31     import java.util.concurrent.Future;
32 jsr166 1.26 import java.util.concurrent.Phaser;
33 jsr166 1.5 import java.util.concurrent.ThreadLocalRandom;
34 jsr166 1.1 import java.util.concurrent.atomic.AtomicBoolean;
35     import java.util.concurrent.atomic.AtomicLong;
36 jsr166 1.5 import java.util.concurrent.atomic.AtomicReference;
37 jsr166 1.1 import java.util.function.Consumer;
38 jsr166 1.5 import java.util.function.Predicate;
39 jsr166 1.26 import java.util.stream.Collectors;
40 jsr166 1.1
41     import junit.framework.Test;
42    
43     /**
44     * Contains tests applicable to all jdk8+ Collection implementations.
45     * An extension of CollectionTest.
46     */
47     public class Collection8Test extends JSR166TestCase {
48     final CollectionImplementation impl;
49    
50     /** Tests are parameterized by a Collection implementation. */
51     Collection8Test(CollectionImplementation impl, String methodName) {
52     super(methodName);
53     this.impl = impl;
54     }
55    
56     public static Test testSuite(CollectionImplementation impl) {
57     return parameterizedTestSuite(Collection8Test.class,
58     CollectionImplementation.class,
59     impl);
60     }
61    
62 jsr166 1.10 Object bomb() {
63     return new Object() {
64 jsr166 1.48 @Override public boolean equals(Object x) { throw new AssertionError(); }
65     @Override public int hashCode() { throw new AssertionError(); }
66     @Override public String toString() { throw new AssertionError(); }
67 jsr166 1.47 };
68 jsr166 1.10 }
69    
70 jsr166 1.5 /** Checks properties of empty collections. */
71 jsr166 1.24 public void testEmptyMeansEmpty() throws Throwable {
72 jsr166 1.5 Collection c = impl.emptyCollection();
73 jsr166 1.12 emptyMeansEmpty(c);
74    
75 jsr166 1.24 if (c instanceof java.io.Serializable) {
76     try {
77     emptyMeansEmpty(serialClonePossiblyFailing(c));
78     } catch (java.io.NotSerializableException ex) {
79     // excusable when we have a serializable wrapper around
80     // a non-serializable collection, as can happen with:
81     // Vector.subList() => wrapped AbstractList$RandomAccessSubList
82     if (testImplementationDetails
83     && (! c.getClass().getName().matches(
84     "java.util.Collections.*")))
85     throw ex;
86     }
87     }
88 jsr166 1.12
89     Collection clone = cloneableClone(c);
90     if (clone != null)
91     emptyMeansEmpty(clone);
92     }
93    
94 jsr166 1.14 void emptyMeansEmpty(Collection c) throws InterruptedException {
95 jsr166 1.5 assertTrue(c.isEmpty());
96     assertEquals(0, c.size());
97     assertEquals("[]", c.toString());
98 jsr166 1.48 if (c instanceof List<?>) {
99     List x = (List) c;
100     assertEquals(1, x.hashCode());
101     assertEquals(x, Collections.emptyList());
102     assertEquals(Collections.emptyList(), x);
103     assertEquals(-1, x.indexOf(impl.makeElement(86)));
104     assertEquals(-1, x.lastIndexOf(impl.makeElement(99)));
105 jsr166 1.49 assertThrows(
106     IndexOutOfBoundsException.class,
107     () -> x.get(0),
108     () -> x.set(0, impl.makeElement(42)));
109 jsr166 1.48 }
110     else if (c instanceof Set<?>) {
111     assertEquals(0, c.hashCode());
112     assertEquals(c, Collections.emptySet());
113     assertEquals(Collections.emptySet(), c);
114     }
115 jsr166 1.5 {
116     Object[] a = c.toArray();
117     assertEquals(0, a.length);
118     assertSame(Object[].class, a.getClass());
119     }
120     {
121     Object[] a = new Object[0];
122     assertSame(a, c.toArray(a));
123     }
124     {
125     Integer[] a = new Integer[0];
126     assertSame(a, c.toArray(a));
127     }
128     {
129     Integer[] a = { 1, 2, 3};
130     assertSame(a, c.toArray(a));
131     assertNull(a[0]);
132     assertSame(2, a[1]);
133     assertSame(3, a[2]);
134     }
135     assertIteratorExhausted(c.iterator());
136 jsr166 1.19 Consumer alwaysThrows = e -> { throw new AssertionError(); };
137 jsr166 1.5 c.forEach(alwaysThrows);
138     c.iterator().forEachRemaining(alwaysThrows);
139     c.spliterator().forEachRemaining(alwaysThrows);
140     assertFalse(c.spliterator().tryAdvance(alwaysThrows));
141 jsr166 1.9 if (c.spliterator().hasCharacteristics(Spliterator.SIZED))
142     assertEquals(0, c.spliterator().estimateSize());
143 jsr166 1.10 assertFalse(c.contains(bomb()));
144     assertFalse(c.remove(bomb()));
145 jsr166 1.11 if (c instanceof Queue) {
146 jsr166 1.5 Queue q = (Queue) c;
147     assertNull(q.peek());
148     assertNull(q.poll());
149     }
150 jsr166 1.11 if (c instanceof Deque) {
151 jsr166 1.5 Deque d = (Deque) c;
152     assertNull(d.peekFirst());
153     assertNull(d.peekLast());
154     assertNull(d.pollFirst());
155     assertNull(d.pollLast());
156     assertIteratorExhausted(d.descendingIterator());
157 jsr166 1.9 d.descendingIterator().forEachRemaining(alwaysThrows);
158 jsr166 1.10 assertFalse(d.removeFirstOccurrence(bomb()));
159     assertFalse(d.removeLastOccurrence(bomb()));
160 jsr166 1.5 }
161 jsr166 1.14 if (c instanceof BlockingQueue) {
162     BlockingQueue q = (BlockingQueue) c;
163 jsr166 1.46 assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
164 jsr166 1.14 }
165     if (c instanceof BlockingDeque) {
166     BlockingDeque q = (BlockingDeque) c;
167 jsr166 1.46 assertNull(q.pollFirst(randomExpiredTimeout(), randomTimeUnit()));
168     assertNull(q.pollLast(randomExpiredTimeout(), randomTimeUnit()));
169 jsr166 1.14 }
170 jsr166 1.5 }
171    
172 jsr166 1.14 public void testNullPointerExceptions() throws InterruptedException {
173 jsr166 1.5 Collection c = impl.emptyCollection();
174     assertThrows(
175     NullPointerException.class,
176     () -> c.addAll(null),
177     () -> c.containsAll(null),
178     () -> c.retainAll(null),
179     () -> c.removeAll(null),
180     () -> c.removeIf(null),
181 jsr166 1.6 () -> c.forEach(null),
182     () -> c.iterator().forEachRemaining(null),
183     () -> c.spliterator().forEachRemaining(null),
184     () -> c.spliterator().tryAdvance(null),
185 jsr166 1.57 () -> c.toArray((Object[])null));
186 jsr166 1.5
187     if (!impl.permitsNulls()) {
188     assertThrows(
189     NullPointerException.class,
190     () -> c.add(null));
191     }
192 jsr166 1.14 if (!impl.permitsNulls() && c instanceof Queue) {
193 jsr166 1.5 Queue q = (Queue) c;
194     assertThrows(
195     NullPointerException.class,
196     () -> q.offer(null));
197     }
198 jsr166 1.14 if (!impl.permitsNulls() && c instanceof Deque) {
199 jsr166 1.5 Deque d = (Deque) c;
200     assertThrows(
201     NullPointerException.class,
202     () -> d.addFirst(null),
203     () -> d.addLast(null),
204     () -> d.offerFirst(null),
205     () -> d.offerLast(null),
206 jsr166 1.6 () -> d.push(null),
207     () -> d.descendingIterator().forEachRemaining(null));
208 jsr166 1.5 }
209 jsr166 1.15 if (c instanceof BlockingQueue) {
210 jsr166 1.14 BlockingQueue q = (BlockingQueue) c;
211     assertThrows(
212     NullPointerException.class,
213 jsr166 1.58 () -> q.offer(null, 1L, HOURS),
214     () -> q.put(null));
215 jsr166 1.14 }
216 jsr166 1.15 if (c instanceof BlockingDeque) {
217 jsr166 1.14 BlockingDeque q = (BlockingDeque) c;
218     assertThrows(
219     NullPointerException.class,
220 jsr166 1.58 () -> q.offerFirst(null, 1L, HOURS),
221     () -> q.offerLast(null, 1L, HOURS),
222     () -> q.putFirst(null),
223     () -> q.putLast(null));
224 jsr166 1.14 }
225 jsr166 1.5 }
226    
227     public void testNoSuchElementExceptions() {
228     Collection c = impl.emptyCollection();
229     assertThrows(
230     NoSuchElementException.class,
231     () -> c.iterator().next());
232    
233 jsr166 1.14 if (c instanceof Queue) {
234 jsr166 1.5 Queue q = (Queue) c;
235     assertThrows(
236     NoSuchElementException.class,
237     () -> q.element(),
238     () -> q.remove());
239     }
240 jsr166 1.14 if (c instanceof Deque) {
241 jsr166 1.5 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 jsr166 1.48 if (c instanceof List) {
252     List x = (List) c;
253     assertThrows(
254     NoSuchElementException.class,
255     () -> x.iterator().next(),
256     () -> x.listIterator().next(),
257     () -> x.listIterator(0).next(),
258     () -> x.listIterator().previous(),
259     () -> x.listIterator(0).previous());
260     }
261 jsr166 1.5 }
262    
263     public void testRemoveIf() {
264     Collection c = impl.emptyCollection();
265 jsr166 1.22 boolean ordered =
266     c.spliterator().hasCharacteristics(Spliterator.ORDERED);
267 jsr166 1.5 ThreadLocalRandom rnd = ThreadLocalRandom.current();
268     int n = rnd.nextInt(6);
269     for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
270     AtomicReference threwAt = new AtomicReference(null);
271 jsr166 1.18 List orig = rnd.nextBoolean()
272     ? new ArrayList(c)
273     : Arrays.asList(c.toArray());
274    
275     // Merely creating an iterator can change ArrayBlockingQueue behavior
276     Iterator it = rnd.nextBoolean() ? c.iterator() : null;
277    
278     ArrayList survivors = new ArrayList();
279 jsr166 1.5 ArrayList accepts = new ArrayList();
280     ArrayList rejects = new ArrayList();
281 jsr166 1.18
282 jsr166 1.19 Predicate randomPredicate = e -> {
283 jsr166 1.5 assertNull(threwAt.get());
284     switch (rnd.nextInt(3)) {
285     case 0: accepts.add(e); return true;
286     case 1: rejects.add(e); return false;
287     case 2: threwAt.set(e); throw new ArithmeticException();
288     default: throw new AssertionError();
289     }
290     };
291     try {
292 jsr166 1.7 try {
293     boolean modified = c.removeIf(randomPredicate);
294 jsr166 1.18 assertNull(threwAt.get());
295     assertEquals(modified, accepts.size() > 0);
296     assertEquals(modified, rejects.size() != n);
297     assertEquals(accepts.size() + rejects.size(), n);
298 jsr166 1.22 if (ordered) {
299     assertEquals(rejects,
300     Arrays.asList(c.toArray()));
301     } else {
302     assertEquals(new HashSet(rejects),
303     new HashSet(Arrays.asList(c.toArray())));
304     }
305 jsr166 1.18 } catch (ArithmeticException ok) {
306     assertNotNull(threwAt.get());
307     assertTrue(c.contains(threwAt.get()));
308     }
309     if (it != null && impl.isConcurrent())
310     // check for weakly consistent iterator
311     while (it.hasNext()) assertTrue(orig.contains(it.next()));
312     switch (rnd.nextInt(4)) {
313     case 0: survivors.addAll(c); break;
314     case 1: survivors.addAll(Arrays.asList(c.toArray())); break;
315 jsr166 1.28 case 2: c.forEach(survivors::add); break;
316 jsr166 1.18 case 3: for (Object e : c) survivors.add(e); break;
317     }
318     assertTrue(orig.containsAll(accepts));
319     assertTrue(orig.containsAll(rejects));
320     assertTrue(orig.containsAll(survivors));
321     assertTrue(orig.containsAll(c));
322     assertTrue(c.containsAll(rejects));
323 jsr166 1.7 assertTrue(c.containsAll(survivors));
324     assertTrue(survivors.containsAll(rejects));
325 jsr166 1.22 if (threwAt.get() == null) {
326     assertEquals(n - accepts.size(), c.size());
327     for (Object x : accepts) assertFalse(c.contains(x));
328     } else {
329     // Two acceptable behaviors: entire removeIf call is one
330     // transaction, or each element processed is one transaction.
331     assertTrue(n == c.size() || n == c.size() + accepts.size());
332     int k = 0;
333     for (Object x : accepts) if (c.contains(x)) k++;
334     assertTrue(k == accepts.size() || k == 0);
335     }
336 jsr166 1.7 } catch (Throwable ex) {
337 jsr166 1.5 System.err.println(impl.klazz());
338 jsr166 1.23 // c is at risk of corruption if we got here, so be lenient
339     try { System.err.printf("c=%s%n", c); }
340     catch (Throwable t) { t.printStackTrace(); }
341 jsr166 1.7 System.err.printf("n=%d%n", n);
342 jsr166 1.18 System.err.printf("orig=%s%n", orig);
343 jsr166 1.7 System.err.printf("accepts=%s%n", accepts);
344     System.err.printf("rejects=%s%n", rejects);
345 jsr166 1.8 System.err.printf("survivors=%s%n", survivors);
346 jsr166 1.18 System.err.printf("threwAt=%s%n", threwAt.get());
347 jsr166 1.7 throw ex;
348 jsr166 1.5 }
349     }
350    
351     /**
352 jsr166 1.39 * All elements removed in the middle of CONCURRENT traversal.
353     */
354     public void testElementRemovalDuringTraversal() {
355     Collection c = impl.emptyCollection();
356     ThreadLocalRandom rnd = ThreadLocalRandom.current();
357     int n = rnd.nextInt(6);
358     ArrayList copy = new ArrayList();
359     for (int i = 0; i < n; i++) {
360     Object x = impl.makeElement(i);
361     copy.add(x);
362     c.add(x);
363     }
364     ArrayList iterated = new ArrayList();
365     ArrayList spliterated = new ArrayList();
366     Spliterator s = c.spliterator();
367     Iterator it = c.iterator();
368     for (int i = rnd.nextInt(n + 1); --i >= 0; ) {
369     assertTrue(s.tryAdvance(spliterated::add));
370     if (rnd.nextBoolean()) assertTrue(it.hasNext());
371     iterated.add(it.next());
372     }
373     Consumer alwaysThrows = e -> { throw new AssertionError(); };
374     if (s.hasCharacteristics(Spliterator.CONCURRENT)) {
375     c.clear(); // TODO: many more removal methods
376     if (testImplementationDetails
377     && !(c instanceof java.util.concurrent.ArrayBlockingQueue)) {
378     if (rnd.nextBoolean())
379     assertFalse(s.tryAdvance(alwaysThrows));
380     else
381     s.forEachRemaining(alwaysThrows);
382     }
383     if (it.hasNext()) iterated.add(it.next());
384     if (rnd.nextBoolean()) assertIteratorExhausted(it);
385     }
386     assertTrue(copy.containsAll(iterated));
387     assertTrue(copy.containsAll(spliterated));
388     }
389    
390     /**
391     * Some elements randomly disappear in the middle of traversal.
392     */
393     public void testRandomElementRemovalDuringTraversal() {
394     Collection c = impl.emptyCollection();
395     ThreadLocalRandom rnd = ThreadLocalRandom.current();
396     int n = rnd.nextInt(6);
397     ArrayList copy = new ArrayList();
398     for (int i = 0; i < n; i++) {
399     Object x = impl.makeElement(i);
400     copy.add(x);
401     c.add(x);
402     }
403     ArrayList iterated = new ArrayList();
404     ArrayList spliterated = new ArrayList();
405     ArrayList removed = new ArrayList();
406     Spliterator s = c.spliterator();
407     Iterator it = c.iterator();
408     if (! (s.hasCharacteristics(Spliterator.CONCURRENT) ||
409     s.hasCharacteristics(Spliterator.IMMUTABLE)))
410     return;
411     for (int i = rnd.nextInt(n + 1); --i >= 0; ) {
412     assertTrue(s.tryAdvance(e -> {}));
413     if (rnd.nextBoolean()) assertTrue(it.hasNext());
414     it.next();
415     }
416     Consumer alwaysThrows = e -> { throw new AssertionError(); };
417     // TODO: many more removal methods
418     if (rnd.nextBoolean()) {
419     for (Iterator z = c.iterator(); z.hasNext(); ) {
420     Object e = z.next();
421     if (rnd.nextBoolean()) {
422     try {
423     z.remove();
424     } catch (UnsupportedOperationException ok) { return; }
425     removed.add(e);
426     }
427     }
428     } else {
429     Predicate randomlyRemove = e -> {
430     if (rnd.nextBoolean()) { removed.add(e); return true; }
431     else return false;
432     };
433     c.removeIf(randomlyRemove);
434     }
435     s.forEachRemaining(spliterated::add);
436     while (it.hasNext())
437     iterated.add(it.next());
438     assertTrue(copy.containsAll(iterated));
439     assertTrue(copy.containsAll(spliterated));
440     assertTrue(copy.containsAll(removed));
441     if (s.hasCharacteristics(Spliterator.CONCURRENT)) {
442     ArrayList iteratedAndRemoved = new ArrayList(iterated);
443     ArrayList spliteratedAndRemoved = new ArrayList(spliterated);
444     iteratedAndRemoved.retainAll(removed);
445     spliteratedAndRemoved.retainAll(removed);
446     assertTrue(iteratedAndRemoved.size() <= 1);
447     assertTrue(spliteratedAndRemoved.size() <= 1);
448     if (testImplementationDetails
449     && !(c instanceof java.util.concurrent.ArrayBlockingQueue))
450     assertTrue(spliteratedAndRemoved.isEmpty());
451     }
452     }
453    
454     /**
455 jsr166 1.5 * Various ways of traversing a collection yield same elements
456     */
457 jsr166 1.41 public void testTraversalEquivalence() {
458 jsr166 1.5 Collection c = impl.emptyCollection();
459     ThreadLocalRandom rnd = ThreadLocalRandom.current();
460     int n = rnd.nextInt(6);
461     for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
462     ArrayList iterated = new ArrayList();
463     ArrayList iteratedForEachRemaining = new ArrayList();
464 jsr166 1.13 ArrayList tryAdvanced = new ArrayList();
465 jsr166 1.5 ArrayList spliterated = new ArrayList();
466 jsr166 1.33 ArrayList splitonced = new ArrayList();
467 jsr166 1.13 ArrayList forEached = new ArrayList();
468 jsr166 1.32 ArrayList streamForEached = new ArrayList();
469     ConcurrentLinkedQueue parallelStreamForEached = new ConcurrentLinkedQueue();
470 jsr166 1.13 ArrayList removeIfed = new ArrayList();
471 jsr166 1.5 for (Object x : c) iterated.add(x);
472 jsr166 1.28 c.iterator().forEachRemaining(iteratedForEachRemaining::add);
473 jsr166 1.13 for (Spliterator s = c.spliterator();
474 jsr166 1.28 s.tryAdvance(tryAdvanced::add); ) {}
475     c.spliterator().forEachRemaining(spliterated::add);
476 jsr166 1.33 { // trySplit returns "strict prefix"
477     Spliterator s1 = c.spliterator(), s2 = s1.trySplit();
478     if (s2 != null) s2.forEachRemaining(splitonced::add);
479     s1.forEachRemaining(splitonced::add);
480     }
481 jsr166 1.28 c.forEach(forEached::add);
482 jsr166 1.32 c.stream().forEach(streamForEached::add);
483     c.parallelStream().forEach(parallelStreamForEached::add);
484 jsr166 1.13 c.removeIf(e -> { removeIfed.add(e); return false; });
485 jsr166 1.5 boolean ordered =
486     c.spliterator().hasCharacteristics(Spliterator.ORDERED);
487     if (c instanceof List || c instanceof Deque)
488     assertTrue(ordered);
489 jsr166 1.32 HashSet cset = new HashSet(c);
490     assertEquals(cset, new HashSet(parallelStreamForEached));
491 jsr166 1.5 if (ordered) {
492     assertEquals(iterated, iteratedForEachRemaining);
493 jsr166 1.13 assertEquals(iterated, tryAdvanced);
494 jsr166 1.5 assertEquals(iterated, spliterated);
495 jsr166 1.33 assertEquals(iterated, splitonced);
496 jsr166 1.13 assertEquals(iterated, forEached);
497 jsr166 1.32 assertEquals(iterated, streamForEached);
498 jsr166 1.13 assertEquals(iterated, removeIfed);
499 jsr166 1.5 } else {
500     assertEquals(cset, new HashSet(iterated));
501     assertEquals(cset, new HashSet(iteratedForEachRemaining));
502 jsr166 1.13 assertEquals(cset, new HashSet(tryAdvanced));
503 jsr166 1.5 assertEquals(cset, new HashSet(spliterated));
504 jsr166 1.33 assertEquals(cset, new HashSet(splitonced));
505 jsr166 1.13 assertEquals(cset, new HashSet(forEached));
506 jsr166 1.32 assertEquals(cset, new HashSet(streamForEached));
507 jsr166 1.13 assertEquals(cset, new HashSet(removeIfed));
508 jsr166 1.5 }
509     if (c instanceof Deque) {
510     Deque d = (Deque) c;
511     ArrayList descending = new ArrayList();
512     ArrayList descendingForEachRemaining = new ArrayList();
513     for (Iterator it = d.descendingIterator(); it.hasNext(); )
514     descending.add(it.next());
515     d.descendingIterator().forEachRemaining(
516     e -> descendingForEachRemaining.add(e));
517     Collections.reverse(descending);
518     Collections.reverse(descendingForEachRemaining);
519     assertEquals(iterated, descending);
520     assertEquals(iterated, descendingForEachRemaining);
521     }
522     }
523    
524     /**
525 jsr166 1.42 * Iterator.forEachRemaining has same behavior as Iterator's
526     * default implementation.
527     */
528     public void testForEachRemainingConsistentWithDefaultImplementation() {
529     Collection c = impl.emptyCollection();
530     if (!testImplementationDetails
531     || c.getClass() == java.util.LinkedList.class)
532     return;
533     ThreadLocalRandom rnd = ThreadLocalRandom.current();
534     int n = 1 + rnd.nextInt(3);
535     for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
536     ArrayList iterated = new ArrayList();
537     ArrayList iteratedForEachRemaining = new ArrayList();
538     Iterator it1 = c.iterator();
539     Iterator it2 = c.iterator();
540     assertTrue(it1.hasNext());
541     assertTrue(it2.hasNext());
542     c.clear();
543     Object r1, r2;
544     try {
545     while (it1.hasNext()) iterated.add(it1.next());
546     r1 = iterated;
547     } catch (ConcurrentModificationException ex) {
548     r1 = ConcurrentModificationException.class;
549     assertFalse(impl.isConcurrent());
550     }
551     try {
552     it2.forEachRemaining(iteratedForEachRemaining::add);
553     r2 = iteratedForEachRemaining;
554     } catch (ConcurrentModificationException ex) {
555     r2 = ConcurrentModificationException.class;
556 jsr166 1.44 assertFalse(impl.isConcurrent());
557 jsr166 1.42 }
558     assertEquals(r1, r2);
559     }
560    
561     /**
562 jsr166 1.5 * Calling Iterator#remove() after Iterator#forEachRemaining
563 jsr166 1.21 * should (maybe) remove last element
564 jsr166 1.5 */
565     public void testRemoveAfterForEachRemaining() {
566     Collection c = impl.emptyCollection();
567     ThreadLocalRandom rnd = ThreadLocalRandom.current();
568 jsr166 1.53 ArrayList copy = new ArrayList();
569     boolean ordered = c.spliterator().hasCharacteristics(Spliterator.ORDERED);
570 jsr166 1.25 testCollection: {
571 jsr166 1.5 int n = 3 + rnd.nextInt(2);
572 jsr166 1.53 for (int i = 0; i < n; i++) {
573     Object x = impl.makeElement(i);
574     c.add(x);
575     copy.add(x);
576     }
577 jsr166 1.5 Iterator it = c.iterator();
578 jsr166 1.53 if (ordered) {
579     if (rnd.nextBoolean()) assertTrue(it.hasNext());
580     assertEquals(impl.makeElement(0), it.next());
581     if (rnd.nextBoolean()) assertTrue(it.hasNext());
582     assertEquals(impl.makeElement(1), it.next());
583     } else {
584     if (rnd.nextBoolean()) assertTrue(it.hasNext());
585     assertTrue(copy.contains(it.next()));
586     if (rnd.nextBoolean()) assertTrue(it.hasNext());
587     assertTrue(copy.contains(it.next()));
588     }
589 jsr166 1.54 if (rnd.nextBoolean()) assertTrue(it.hasNext());
590 jsr166 1.53 it.forEachRemaining(
591     e -> {
592     assertTrue(c.contains(e));
593     assertTrue(copy.contains(e));});
594 jsr166 1.21 if (testImplementationDetails) {
595     if (c instanceof java.util.concurrent.ArrayBlockingQueue) {
596     assertIteratorExhausted(it);
597     } else {
598 jsr166 1.25 try { it.remove(); }
599     catch (UnsupportedOperationException ok) {
600     break testCollection;
601     }
602 jsr166 1.21 assertEquals(n - 1, c.size());
603 jsr166 1.53 if (ordered) {
604     for (int i = 0; i < n - 1; i++)
605     assertTrue(c.contains(impl.makeElement(i)));
606     assertFalse(c.contains(impl.makeElement(n - 1)));
607     }
608 jsr166 1.21 }
609     }
610 jsr166 1.5 }
611     if (c instanceof Deque) {
612     Deque d = (Deque) impl.emptyCollection();
613 jsr166 1.53 assertTrue(ordered);
614 jsr166 1.5 int n = 3 + rnd.nextInt(2);
615     for (int i = 0; i < n; i++) d.add(impl.makeElement(i));
616     Iterator it = d.descendingIterator();
617     assertTrue(it.hasNext());
618     assertEquals(impl.makeElement(n - 1), it.next());
619     assertTrue(it.hasNext());
620     assertEquals(impl.makeElement(n - 2), it.next());
621 jsr166 1.21 it.forEachRemaining(e -> assertTrue(c.contains(e)));
622     if (testImplementationDetails) {
623     it.remove();
624     assertEquals(n - 1, d.size());
625     for (int i = 1; i < n; i++)
626     assertTrue(d.contains(impl.makeElement(i)));
627     assertFalse(d.contains(impl.makeElement(0)));
628     }
629 jsr166 1.5 }
630     }
631    
632 jsr166 1.1 /**
633     * stream().forEach returns elements in the collection
634     */
635 jsr166 1.3 public void testStreamForEach() throws Throwable {
636 jsr166 1.1 final Collection c = impl.emptyCollection();
637     final AtomicLong count = new AtomicLong(0L);
638     final Object x = impl.makeElement(1);
639     final Object y = impl.makeElement(2);
640     final ArrayList found = new ArrayList();
641 jsr166 1.20 Consumer<Object> spy = o -> found.add(o);
642 jsr166 1.1 c.stream().forEach(spy);
643     assertTrue(found.isEmpty());
644    
645     assertTrue(c.add(x));
646     c.stream().forEach(spy);
647     assertEquals(Collections.singletonList(x), found);
648     found.clear();
649    
650     assertTrue(c.add(y));
651     c.stream().forEach(spy);
652     assertEquals(2, found.size());
653     assertTrue(found.contains(x));
654     assertTrue(found.contains(y));
655     found.clear();
656    
657     c.clear();
658     c.stream().forEach(spy);
659     assertTrue(found.isEmpty());
660     }
661    
662 jsr166 1.3 public void testStreamForEachConcurrentStressTest() throws Throwable {
663     if (!impl.isConcurrent()) return;
664     final Collection c = impl.emptyCollection();
665     final long testDurationMillis = timeoutMillis();
666     final AtomicBoolean done = new AtomicBoolean(false);
667     final Object elt = impl.makeElement(1);
668     final Future<?> f1, f2;
669     final ExecutorService pool = Executors.newCachedThreadPool();
670     try (PoolCleaner cleaner = cleaner(pool, done)) {
671     final CountDownLatch threadsStarted = new CountDownLatch(2);
672     Runnable checkElt = () -> {
673     threadsStarted.countDown();
674     while (!done.get())
675 jsr166 1.20 c.stream().forEach(x -> assertSame(x, elt)); };
676 jsr166 1.3 Runnable addRemove = () -> {
677     threadsStarted.countDown();
678     while (!done.get()) {
679     assertTrue(c.add(elt));
680     assertTrue(c.remove(elt));
681     }};
682     f1 = pool.submit(checkElt);
683     f2 = pool.submit(addRemove);
684     Thread.sleep(testDurationMillis);
685     }
686     assertNull(f1.get(0L, MILLISECONDS));
687     assertNull(f2.get(0L, MILLISECONDS));
688     }
689    
690     /**
691     * collection.forEach returns elements in the collection
692     */
693     public void testForEach() throws Throwable {
694     final Collection c = impl.emptyCollection();
695     final AtomicLong count = new AtomicLong(0L);
696     final Object x = impl.makeElement(1);
697     final Object y = impl.makeElement(2);
698     final ArrayList found = new ArrayList();
699 jsr166 1.20 Consumer<Object> spy = o -> found.add(o);
700 jsr166 1.3 c.forEach(spy);
701     assertTrue(found.isEmpty());
702    
703     assertTrue(c.add(x));
704     c.forEach(spy);
705     assertEquals(Collections.singletonList(x), found);
706     found.clear();
707    
708     assertTrue(c.add(y));
709     c.forEach(spy);
710     assertEquals(2, found.size());
711     assertTrue(found.contains(x));
712     assertTrue(found.contains(y));
713     found.clear();
714    
715     c.clear();
716     c.forEach(spy);
717     assertTrue(found.isEmpty());
718     }
719    
720 jsr166 1.38 /** TODO: promote to a common utility */
721     static <T> T chooseOne(T ... ts) {
722     return ts[ThreadLocalRandom.current().nextInt(ts.length)];
723     }
724    
725     /** TODO: more random adders and removers */
726     static <E> Runnable adderRemover(Collection<E> c, E e) {
727     return chooseOne(
728     () -> {
729     assertTrue(c.add(e));
730     assertTrue(c.contains(e));
731     assertTrue(c.remove(e));
732     assertFalse(c.contains(e));
733     },
734     () -> {
735     assertTrue(c.add(e));
736     assertTrue(c.contains(e));
737     assertTrue(c.removeIf(x -> x == e));
738     assertFalse(c.contains(e));
739     },
740     () -> {
741     assertTrue(c.add(e));
742     assertTrue(c.contains(e));
743     for (Iterator it = c.iterator();; )
744     if (it.next() == e) {
745     try { it.remove(); }
746     catch (UnsupportedOperationException ok) {
747     c.remove(e);
748     }
749     break;
750     }
751     assertFalse(c.contains(e));
752     });
753     }
754    
755 jsr166 1.26 /**
756 jsr166 1.45 * Concurrent Spliterators, once exhausted, stay exhausted.
757     */
758     public void testStickySpliteratorExhaustion() throws Throwable {
759     if (!impl.isConcurrent()) return;
760     if (!testImplementationDetails) return;
761     final ThreadLocalRandom rnd = ThreadLocalRandom.current();
762     final Consumer alwaysThrows = e -> { throw new AssertionError(); };
763     final Collection c = impl.emptyCollection();
764     final Spliterator s = c.spliterator();
765     if (rnd.nextBoolean()) {
766     assertFalse(s.tryAdvance(alwaysThrows));
767     } else {
768     s.forEachRemaining(alwaysThrows);
769     }
770     final Object one = impl.makeElement(1);
771     // Spliterator should not notice added element
772     c.add(one);
773     if (rnd.nextBoolean()) {
774     assertFalse(s.tryAdvance(alwaysThrows));
775     } else {
776     s.forEachRemaining(alwaysThrows);
777     }
778     }
779    
780     /**
781 jsr166 1.26 * Motley crew of threads concurrently randomly hammer the collection.
782     */
783     public void testDetectRaces() throws Throwable {
784 jsr166 1.1 if (!impl.isConcurrent()) return;
785 jsr166 1.26 final ThreadLocalRandom rnd = ThreadLocalRandom.current();
786 jsr166 1.1 final Collection c = impl.emptyCollection();
787 jsr166 1.34 final long testDurationMillis
788     = expensiveTests ? LONG_DELAY_MS : timeoutMillis();
789 jsr166 1.1 final AtomicBoolean done = new AtomicBoolean(false);
790 jsr166 1.26 final Object one = impl.makeElement(1);
791     final Object two = impl.makeElement(2);
792 jsr166 1.35 final Consumer checkSanity = x -> assertTrue(x == one || x == two);
793 jsr166 1.36 final Consumer<Object[]> checkArraySanity = array -> {
794 jsr166 1.37 // assertTrue(array.length <= 2); // duplicates are permitted
795 jsr166 1.36 for (Object x : array) assertTrue(x == one || x == two);
796     };
797 jsr166 1.29 final Object[] emptyArray =
798     (Object[]) java.lang.reflect.Array.newInstance(one.getClass(), 0);
799 jsr166 1.26 final List<Future<?>> futures;
800     final Phaser threadsStarted = new Phaser(1); // register this thread
801 jsr166 1.27 final Runnable[] frobbers = {
802 jsr166 1.32 () -> c.forEach(checkSanity),
803     () -> c.stream().forEach(checkSanity),
804     () -> c.parallelStream().forEach(checkSanity),
805 jsr166 1.26 () -> c.spliterator().trySplit(),
806     () -> {
807     Spliterator s = c.spliterator();
808 jsr166 1.32 s.tryAdvance(checkSanity);
809 jsr166 1.26 s.trySplit();
810     },
811     () -> {
812     Spliterator s = c.spliterator();
813 jsr166 1.32 do {} while (s.tryAdvance(checkSanity));
814 jsr166 1.29 },
815 jsr166 1.32 () -> { for (Object x : c) checkSanity.accept(x); },
816 jsr166 1.36 () -> checkArraySanity.accept(c.toArray()),
817     () -> checkArraySanity.accept(c.toArray(emptyArray)),
818 jsr166 1.29 () -> {
819 jsr166 1.38 Object[] a = new Object[5];
820     Object three = impl.makeElement(3);
821     Arrays.fill(a, 0, a.length, three);
822     Object[] x = c.toArray(a);
823     if (x == a)
824     for (int i = 0; i < a.length && a[i] != null; i++)
825     checkSanity.accept(a[i]);
826     // A careful reading of the spec does not support:
827     // for (i++; i < a.length; i++) assertSame(three, a[i]);
828     else
829     checkArraySanity.accept(x);
830     },
831     adderRemover(c, one),
832     adderRemover(c, two),
833 jsr166 1.27 };
834     final List<Runnable> tasks =
835     Arrays.stream(frobbers)
836 jsr166 1.26 .filter(task -> rnd.nextBoolean()) // random subset
837     .map(task -> (Runnable) () -> {
838     threadsStarted.arriveAndAwaitAdvance();
839     while (!done.get())
840     task.run();
841     })
842     .collect(Collectors.toList());
843 jsr166 1.2 final ExecutorService pool = Executors.newCachedThreadPool();
844     try (PoolCleaner cleaner = cleaner(pool, done)) {
845 jsr166 1.26 threadsStarted.bulkRegister(tasks.size());
846     futures = tasks.stream()
847 jsr166 1.28 .map(pool::submit)
848 jsr166 1.26 .collect(Collectors.toList());
849     threadsStarted.arriveAndDeregister();
850 jsr166 1.2 Thread.sleep(testDurationMillis);
851     }
852 jsr166 1.26 for (Future future : futures)
853     assertNull(future.get(0L, MILLISECONDS));
854 jsr166 1.1 }
855    
856 jsr166 1.30 /**
857     * Spliterators are either IMMUTABLE or truly late-binding or, if
858     * concurrent, use the same "late-binding style" of returning
859     * elements added between creation and first use.
860     */
861     public void testLateBindingStyle() {
862     if (!testImplementationDetails) return;
863 jsr166 1.31 if (impl.klazz() == ArrayList.class) return; // for jdk8
864 jsr166 1.30 // Immutable (snapshot) spliterators are exempt
865     if (impl.emptyCollection().spliterator()
866     .hasCharacteristics(Spliterator.IMMUTABLE))
867     return;
868     final Object one = impl.makeElement(1);
869     {
870     final Collection c = impl.emptyCollection();
871     final Spliterator split = c.spliterator();
872     c.add(one);
873     assertTrue(split.tryAdvance(e -> { assertSame(e, one); }));
874     assertFalse(split.tryAdvance(e -> { throw new AssertionError(); }));
875     assertTrue(c.contains(one));
876     }
877     {
878     final AtomicLong count = new AtomicLong(0);
879     final Collection c = impl.emptyCollection();
880     final Spliterator split = c.spliterator();
881     c.add(one);
882     split.forEachRemaining(
883     e -> { assertSame(e, one); count.getAndIncrement(); });
884     assertEquals(1L, count.get());
885     assertFalse(split.tryAdvance(e -> { throw new AssertionError(); }));
886     assertTrue(c.contains(one));
887     }
888     }
889    
890 jsr166 1.40 /**
891     * Spliterator.getComparator throws IllegalStateException iff the
892     * spliterator does not report SORTED.
893     */
894     public void testGetComparator_IllegalStateException() {
895     Collection c = impl.emptyCollection();
896     Spliterator s = c.spliterator();
897     boolean reportsSorted = s.hasCharacteristics(Spliterator.SORTED);
898     try {
899     s.getComparator();
900     assertTrue(reportsSorted);
901     } catch (IllegalStateException ex) {
902     assertFalse(reportsSorted);
903     }
904     }
905    
906 jsr166 1.51 public void testCollectionCopies() throws Exception {
907 jsr166 1.50 ThreadLocalRandom rnd = ThreadLocalRandom.current();
908     Collection c = impl.emptyCollection();
909 jsr166 1.51 for (int n = rnd.nextInt(4); n--> 0; )
910 jsr166 1.50 c.add(impl.makeElement(rnd.nextInt()));
911     assertEquals(c, c);
912 jsr166 1.51 if (c instanceof List)
913     assertCollectionsEquals(c, new ArrayList(c));
914     else if (c instanceof Set)
915     assertCollectionsEquals(c, new HashSet(c));
916     else if (c instanceof Deque)
917     assertCollectionsEquivalent(c, new ArrayDeque(c));
918    
919     Collection clone = cloneableClone(c);
920     if (clone != null) {
921     assertSame(c.getClass(), clone.getClass());
922     assertCollectionsEquivalent(c, clone);
923 jsr166 1.50 }
924 jsr166 1.51 try {
925     Collection serialClone = serialClonePossiblyFailing(c);
926     assertSame(c.getClass(), serialClone.getClass());
927     assertCollectionsEquivalent(c, serialClone);
928     } catch (java.io.NotSerializableException acceptable) {}
929 jsr166 1.50 }
930    
931 jsr166 1.56 public void testReplaceAllIsNotStructuralModification() {
932 jsr166 1.52 Collection c = impl.emptyCollection();
933     if (!(c instanceof List))
934     return;
935     List list = (List) c;
936     ThreadLocalRandom rnd = ThreadLocalRandom.current();
937     for (int n = rnd.nextInt(2, 10); n--> 0; )
938     list.add(impl.makeElement(rnd.nextInt()));
939     ArrayList copy = new ArrayList(list);
940     int size = list.size(), half = size / 2;
941     Iterator it = list.iterator();
942     for (int i = 0; i < half; i++)
943     assertEquals(it.next(), copy.get(i));
944     list.replaceAll(n -> n);
945     // ConcurrentModificationException must not be thrown here.
946     for (int i = half; i < size; i++)
947     assertEquals(it.next(), copy.get(i));
948     }
949    
950 jsr166 1.4 // public void testCollection8DebugFail() {
951     // fail(impl.klazz().getSimpleName());
952     // }
953 jsr166 1.1 }