ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/Collection8Test.java
Revision: 1.22
Committed: Sun Nov 13 02:10:10 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.21: +20 -3 lines
Log Message:
Tolerate reentrant read access in removeIf

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