ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/Collection8Test.java
Revision: 1.41
Committed: Mon Dec 12 03:50:15 2016 UTC (7 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.40: +1 -1 lines
Log Message:
testIteratorEquivalence -> testTraversalEquivalence

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