ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/Collection8Test.java
(Generate patch)

Comparing jsr166/src/test/tck/Collection8Test.java (file contents):
Revision 1.5 by jsr166, Tue Oct 25 01:32:55 2016 UTC vs.
Revision 1.38 by jsr166, Wed Dec 7 22:03:41 2016 UTC

# Line 5 | Line 5
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;
# Line 17 | Line 19 | 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.ConcurrentLinkedQueue;
25   import java.util.concurrent.CountDownLatch;
26   import java.util.concurrent.Executors;
27   import java.util.concurrent.ExecutorService;
28   import java.util.concurrent.Future;
29 + import java.util.concurrent.Phaser;
30   import java.util.concurrent.ThreadLocalRandom;
31   import java.util.concurrent.atomic.AtomicBoolean;
32   import java.util.concurrent.atomic.AtomicLong;
33   import java.util.concurrent.atomic.AtomicReference;
34   import java.util.function.Consumer;
35   import java.util.function.Predicate;
36 + import java.util.stream.Collectors;
37  
38   import junit.framework.Test;
39  
# Line 49 | Line 56 | public class Collection8Test extends JSR
56                                        impl);
57      }
58  
59 +    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      /** Checks properties of empty collections. */
67 <    public void testEmptyMeansEmpty() {
67 >    public void testEmptyMeansEmpty() throws Throwable {
68          Collection c = impl.emptyCollection();
69 +        emptyMeansEmpty(c);
70 +
71 +        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 +
85 +        Collection clone = cloneableClone(c);
86 +        if (clone != null)
87 +            emptyMeansEmpty(clone);
88 +    }
89 +
90 +    void emptyMeansEmpty(Collection c) throws InterruptedException {
91          assertTrue(c.isEmpty());
92          assertEquals(0, c.size());
93          assertEquals("[]", c.toString());
# Line 76 | Line 112 | public class Collection8Test extends JSR
112              assertSame(3, a[2]);
113          }
114          assertIteratorExhausted(c.iterator());
115 <        Consumer alwaysThrows = (e) -> { throw new AssertionError(); };
115 >        Consumer alwaysThrows = e -> { throw new AssertionError(); };
116          c.forEach(alwaysThrows);
117          c.iterator().forEachRemaining(alwaysThrows);
118          c.spliterator().forEachRemaining(alwaysThrows);
119          assertFalse(c.spliterator().tryAdvance(alwaysThrows));
120 <        if (Queue.class.isAssignableFrom(impl.klazz())) {
120 >        if (c.spliterator().hasCharacteristics(Spliterator.SIZED))
121 >            assertEquals(0, c.spliterator().estimateSize());
122 >        assertFalse(c.contains(bomb()));
123 >        assertFalse(c.remove(bomb()));
124 >        if (c instanceof Queue) {
125              Queue q = (Queue) c;
126              assertNull(q.peek());
127              assertNull(q.poll());
128          }
129 <        if (Deque.class.isAssignableFrom(impl.klazz())) {
129 >        if (c instanceof Deque) {
130              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 +            d.descendingIterator().forEachRemaining(alwaysThrows);
137 +            assertFalse(d.removeFirstOccurrence(bomb()));
138 +            assertFalse(d.removeLastOccurrence(bomb()));
139 +        }
140 +        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      }
150  
151 <    public void testNullPointerExceptions() {
151 >    public void testNullPointerExceptions() throws InterruptedException {
152          Collection c = impl.emptyCollection();
153          assertThrows(
154              NullPointerException.class,
# Line 105 | Line 157 | public class Collection8Test extends JSR
157              () -> c.retainAll(null),
158              () -> c.removeAll(null),
159              () -> c.removeIf(null),
160 +            () -> c.forEach(null),
161 +            () -> c.iterator().forEachRemaining(null),
162 +            () -> c.spliterator().forEachRemaining(null),
163 +            () -> c.spliterator().tryAdvance(null),
164              () -> c.toArray(null));
165  
166          if (!impl.permitsNulls()) {
# Line 112 | Line 168 | public class Collection8Test extends JSR
168                  NullPointerException.class,
169                  () -> c.add(null));
170          }
171 <        if (!impl.permitsNulls()
116 <            && Queue.class.isAssignableFrom(impl.klazz())) {
171 >        if (!impl.permitsNulls() && c instanceof Queue) {
172              Queue q = (Queue) c;
173              assertThrows(
174                  NullPointerException.class,
175                  () -> q.offer(null));
176          }
177 <        if (!impl.permitsNulls()
123 <            && Deque.class.isAssignableFrom(impl.klazz())) {
177 >        if (!impl.permitsNulls() && c instanceof Deque) {
178              Deque d = (Deque) c;
179              assertThrows(
180                  NullPointerException.class,
# Line 128 | Line 182 | public class Collection8Test extends JSR
182                  () -> d.addLast(null),
183                  () -> d.offerFirst(null),
184                  () -> d.offerLast(null),
185 <                () -> d.push(null));
185 >                () -> d.push(null),
186 >                () -> d.descendingIterator().forEachRemaining(null));
187 >        }
188 >        if (c instanceof BlockingQueue) {
189 >            BlockingQueue q = (BlockingQueue) c;
190 >            assertThrows(
191 >                NullPointerException.class,
192 >                () -> {
193 >                    try { q.offer(null, 1L, HOURS); }
194 >                    catch (InterruptedException ex) {
195 >                        throw new AssertionError(ex);
196 >                    }},
197 >                () -> {
198 >                    try { q.put(null); }
199 >                    catch (InterruptedException ex) {
200 >                        throw new AssertionError(ex);
201 >                    }});
202 >        }
203 >        if (c instanceof BlockingDeque) {
204 >            BlockingDeque q = (BlockingDeque) c;
205 >            assertThrows(
206 >                NullPointerException.class,
207 >                () -> {
208 >                    try { q.offerFirst(null, 1L, HOURS); }
209 >                    catch (InterruptedException ex) {
210 >                        throw new AssertionError(ex);
211 >                    }},
212 >                () -> {
213 >                    try { q.offerLast(null, 1L, HOURS); }
214 >                    catch (InterruptedException ex) {
215 >                        throw new AssertionError(ex);
216 >                    }},
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 >                    }});
227          }
228      }
229  
# Line 138 | Line 233 | public class Collection8Test extends JSR
233              NoSuchElementException.class,
234              () -> c.iterator().next());
235  
236 <        if (Queue.class.isAssignableFrom(impl.klazz())) {
236 >        if (c instanceof Queue) {
237              Queue q = (Queue) c;
238              assertThrows(
239                  NoSuchElementException.class,
240                  () -> q.element(),
241                  () -> q.remove());
242          }
243 <        if (Deque.class.isAssignableFrom(impl.klazz())) {
243 >        if (c instanceof Deque) {
244              Deque d = (Deque) c;
245              assertThrows(
246                  NoSuchElementException.class,
# Line 160 | Line 255 | public class Collection8Test extends JSR
255  
256      public void testRemoveIf() {
257          Collection c = impl.emptyCollection();
258 +        boolean ordered =
259 +            c.spliterator().hasCharacteristics(Spliterator.ORDERED);
260          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 <        ArrayList survivors = new ArrayList(c);
264 >        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          ArrayList accepts = new ArrayList();
273          ArrayList rejects = new ArrayList();
274 <        Predicate randomPredicate = (e) -> {
274 >
275 >        Predicate randomPredicate = e -> {
276              assertNull(threwAt.get());
277              switch (rnd.nextInt(3)) {
278              case 0: accepts.add(e); return true;
# Line 177 | Line 282 | public class Collection8Test extends JSR
282              }
283          };
284          try {
285 <            boolean modified = c.removeIf(randomPredicate);
286 <            if (!modified) {
285 >            try {
286 >                boolean modified = c.removeIf(randomPredicate);
287                  assertNull(threwAt.get());
288 <                assertEquals(n, rejects.size());
289 <                assertEquals(0, accepts.size());
288 >                assertEquals(modified, accepts.size() > 0);
289 >                assertEquals(modified, rejects.size() != n);
290 >                assertEquals(accepts.size() + rejects.size(), n);
291 >                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 >            } catch (ArithmeticException ok) {
299 >                assertNotNull(threwAt.get());
300 >                assertTrue(c.contains(threwAt.get()));
301              }
302 <        } catch (ArithmeticException ok) {}
303 <        survivors.removeAll(accepts);
304 <        if (n - accepts.size() != c.size()) {
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 >            case 2: c.forEach(survivors::add); break;
309 >            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 >            assertTrue(c.containsAll(survivors));
317 >            assertTrue(survivors.containsAll(rejects));
318 >            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 >        } catch (Throwable ex) {
330              System.err.println(impl.klazz());
331 <            System.err.println(c);
332 <            System.err.println(accepts);
333 <            System.err.println(rejects);
334 <            System.err.println(survivors);
335 <            System.err.println(threwAt.get());
336 <        }
337 <        assertEquals(n - accepts.size(), c.size());
338 <        assertTrue(c.containsAll(survivors));
339 <        assertTrue(survivors.containsAll(rejects));
340 <        for (Object x : accepts) assertFalse(c.contains(x));
341 <        if (threwAt.get() == null)
201 <            assertEquals(accepts.size() + rejects.size(), n);
331 >            // 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 >            System.err.printf("n=%d%n", n);
335 >            System.err.printf("orig=%s%n", orig);
336 >            System.err.printf("accepts=%s%n", accepts);
337 >            System.err.printf("rejects=%s%n", rejects);
338 >            System.err.printf("survivors=%s%n", survivors);
339 >            System.err.printf("threwAt=%s%n", threwAt.get());
340 >            throw ex;
341 >        }
342      }
343  
344      /**
# Line 211 | Line 351 | public class Collection8Test extends JSR
351          for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
352          ArrayList iterated = new ArrayList();
353          ArrayList iteratedForEachRemaining = new ArrayList();
354 +        ArrayList tryAdvanced = new ArrayList();
355          ArrayList spliterated = new ArrayList();
356 <        ArrayList foreached = new ArrayList();
356 >        ArrayList splitonced = new ArrayList();
357 >        ArrayList forEached = new ArrayList();
358 >        ArrayList streamForEached = new ArrayList();
359 >        ConcurrentLinkedQueue parallelStreamForEached = new ConcurrentLinkedQueue();
360 >        ArrayList removeIfed = new ArrayList();
361          for (Object x : c) iterated.add(x);
362 <        c.iterator().forEachRemaining(e -> iteratedForEachRemaining.add(e));
363 <        c.spliterator().forEachRemaining(e -> spliterated.add(e));
364 <        c.forEach(e -> foreached.add(e));
362 >        c.iterator().forEachRemaining(iteratedForEachRemaining::add);
363 >        for (Spliterator s = c.spliterator();
364 >             s.tryAdvance(tryAdvanced::add); ) {}
365 >        c.spliterator().forEachRemaining(spliterated::add);
366 >        {                       // trySplit returns "strict prefix"
367 >            Spliterator s1 = c.spliterator(), s2 = s1.trySplit();
368 >            if (s2 != null) s2.forEachRemaining(splitonced::add);
369 >            s1.forEachRemaining(splitonced::add);
370 >        }
371 >        c.forEach(forEached::add);
372 >        c.stream().forEach(streamForEached::add);
373 >        c.parallelStream().forEach(parallelStreamForEached::add);
374 >        c.removeIf(e -> { removeIfed.add(e); return false; });
375          boolean ordered =
376              c.spliterator().hasCharacteristics(Spliterator.ORDERED);
377          if (c instanceof List || c instanceof Deque)
378              assertTrue(ordered);
379 +        HashSet cset = new HashSet(c);
380 +        assertEquals(cset, new HashSet(parallelStreamForEached));
381          if (ordered) {
382              assertEquals(iterated, iteratedForEachRemaining);
383 +            assertEquals(iterated, tryAdvanced);
384              assertEquals(iterated, spliterated);
385 <            assertEquals(iterated, foreached);
385 >            assertEquals(iterated, splitonced);
386 >            assertEquals(iterated, forEached);
387 >            assertEquals(iterated, streamForEached);
388 >            assertEquals(iterated, removeIfed);
389          } else {
229            HashSet cset = new HashSet(c);
390              assertEquals(cset, new HashSet(iterated));
391              assertEquals(cset, new HashSet(iteratedForEachRemaining));
392 +            assertEquals(cset, new HashSet(tryAdvanced));
393              assertEquals(cset, new HashSet(spliterated));
394 <            assertEquals(cset, new HashSet(foreached));
394 >            assertEquals(cset, new HashSet(splitonced));
395 >            assertEquals(cset, new HashSet(forEached));
396 >            assertEquals(cset, new HashSet(streamForEached));
397 >            assertEquals(cset, new HashSet(removeIfed));
398          }
399          if (c instanceof Deque) {
400              Deque d = (Deque) c;
# Line 249 | Line 413 | public class Collection8Test extends JSR
413  
414      /**
415       * Calling Iterator#remove() after Iterator#forEachRemaining
416 <     * should remove last element
416 >     * should (maybe) remove last element
417       */
418      public void testRemoveAfterForEachRemaining() {
419          Collection c = impl.emptyCollection();
420          ThreadLocalRandom rnd = ThreadLocalRandom.current();
421 <        {
421 >        testCollection: {
422              int n = 3 + rnd.nextInt(2);
423              for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
424              Iterator it = c.iterator();
# Line 262 | Line 426 | public class Collection8Test extends JSR
426              assertEquals(impl.makeElement(0), it.next());
427              assertTrue(it.hasNext());
428              assertEquals(impl.makeElement(1), it.next());
429 <            it.forEachRemaining((e) -> {});
430 <            it.remove();
431 <            assertEquals(n - 1, c.size());
432 <            for (int i = 0; i < n - 1; i++)
433 <                assertTrue(c.contains(impl.makeElement(i)));
434 <            assertFalse(c.contains(impl.makeElement(n - 1)));
429 >            it.forEachRemaining(e -> assertTrue(c.contains(e)));
430 >            if (testImplementationDetails) {
431 >                if (c instanceof java.util.concurrent.ArrayBlockingQueue) {
432 >                    assertIteratorExhausted(it);
433 >                } else {
434 >                    try { it.remove(); }
435 >                    catch (UnsupportedOperationException ok) {
436 >                        break testCollection;
437 >                    }
438 >                    assertEquals(n - 1, c.size());
439 >                    for (int i = 0; i < n - 1; i++)
440 >                        assertTrue(c.contains(impl.makeElement(i)));
441 >                    assertFalse(c.contains(impl.makeElement(n - 1)));
442 >                }
443 >            }
444          }
445          if (c instanceof Deque) {
446              Deque d = (Deque) impl.emptyCollection();
# Line 278 | Line 451 | public class Collection8Test extends JSR
451              assertEquals(impl.makeElement(n - 1), it.next());
452              assertTrue(it.hasNext());
453              assertEquals(impl.makeElement(n - 2), it.next());
454 <            it.forEachRemaining((e) -> {});
455 <            it.remove();
456 <            assertEquals(n - 1, d.size());
457 <            for (int i = 1; i < n; i++)
458 <                assertTrue(d.contains(impl.makeElement(i)));
459 <            assertFalse(d.contains(impl.makeElement(0)));
454 >            it.forEachRemaining(e -> assertTrue(c.contains(e)));
455 >            if (testImplementationDetails) {
456 >                it.remove();
457 >                assertEquals(n - 1, d.size());
458 >                for (int i = 1; i < n; i++)
459 >                    assertTrue(d.contains(impl.makeElement(i)));
460 >                assertFalse(d.contains(impl.makeElement(0)));
461 >            }
462          }
463      }
464  
# Line 296 | Line 471 | public class Collection8Test extends JSR
471          final Object x = impl.makeElement(1);
472          final Object y = impl.makeElement(2);
473          final ArrayList found = new ArrayList();
474 <        Consumer<Object> spy = (o) -> { found.add(o); };
474 >        Consumer<Object> spy = o -> found.add(o);
475          c.stream().forEach(spy);
476          assertTrue(found.isEmpty());
477  
# Line 330 | Line 505 | public class Collection8Test extends JSR
505              Runnable checkElt = () -> {
506                  threadsStarted.countDown();
507                  while (!done.get())
508 <                    c.stream().forEach((x) -> { assertSame(x, elt); }); };
508 >                    c.stream().forEach(x -> assertSame(x, elt)); };
509              Runnable addRemove = () -> {
510                  threadsStarted.countDown();
511                  while (!done.get()) {
# Line 354 | Line 529 | public class Collection8Test extends JSR
529          final Object x = impl.makeElement(1);
530          final Object y = impl.makeElement(2);
531          final ArrayList found = new ArrayList();
532 <        Consumer<Object> spy = (o) -> { found.add(o); };
532 >        Consumer<Object> spy = o -> found.add(o);
533          c.forEach(spy);
534          assertTrue(found.isEmpty());
535  
# Line 375 | Line 550 | public class Collection8Test extends JSR
550          assertTrue(found.isEmpty());
551      }
552  
553 <    public void testForEachConcurrentStressTest() throws Throwable {
553 >    /** TODO: promote to a common utility */
554 >    static <T> T chooseOne(T ... ts) {
555 >        return ts[ThreadLocalRandom.current().nextInt(ts.length)];
556 >    }
557 >
558 >    /** TODO: more random adders and removers */
559 >    static <E> Runnable adderRemover(Collection<E> c, E e) {
560 >        return chooseOne(
561 >            () -> {
562 >                assertTrue(c.add(e));
563 >                assertTrue(c.contains(e));
564 >                assertTrue(c.remove(e));
565 >                assertFalse(c.contains(e));
566 >            },
567 >            () -> {
568 >                assertTrue(c.add(e));
569 >                assertTrue(c.contains(e));
570 >                assertTrue(c.removeIf(x -> x == e));
571 >                assertFalse(c.contains(e));
572 >            },
573 >            () -> {
574 >                assertTrue(c.add(e));
575 >                assertTrue(c.contains(e));
576 >                for (Iterator it = c.iterator();; )
577 >                    if (it.next() == e) {
578 >                        try { it.remove(); }
579 >                        catch (UnsupportedOperationException ok) {
580 >                            c.remove(e);
581 >                        }
582 >                        break;
583 >                    }
584 >                assertFalse(c.contains(e));
585 >            });
586 >    }
587 >
588 >    /**
589 >     * Motley crew of threads concurrently randomly hammer the collection.
590 >     */
591 >    public void testDetectRaces() throws Throwable {
592          if (!impl.isConcurrent()) return;
593 +        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
594          final Collection c = impl.emptyCollection();
595 <        final long testDurationMillis = timeoutMillis();
595 >        final long testDurationMillis
596 >            = expensiveTests ? LONG_DELAY_MS : timeoutMillis();
597          final AtomicBoolean done = new AtomicBoolean(false);
598 <        final Object elt = impl.makeElement(1);
599 <        final Future<?> f1, f2;
598 >        final Object one = impl.makeElement(1);
599 >        final Object two = impl.makeElement(2);
600 >        final Consumer checkSanity = x -> assertTrue(x == one || x == two);
601 >        final Consumer<Object[]> checkArraySanity = array -> {
602 >            // assertTrue(array.length <= 2); // duplicates are permitted
603 >            for (Object x : array) assertTrue(x == one || x == two);
604 >        };
605 >        final Object[] emptyArray =
606 >            (Object[]) java.lang.reflect.Array.newInstance(one.getClass(), 0);
607 >        final List<Future<?>> futures;
608 >        final Phaser threadsStarted = new Phaser(1); // register this thread
609 >        final Runnable[] frobbers = {
610 >            () -> c.forEach(checkSanity),
611 >            () -> c.stream().forEach(checkSanity),
612 >            () -> c.parallelStream().forEach(checkSanity),
613 >            () -> c.spliterator().trySplit(),
614 >            () -> {
615 >                Spliterator s = c.spliterator();
616 >                s.tryAdvance(checkSanity);
617 >                s.trySplit();
618 >            },
619 >            () -> {
620 >                Spliterator s = c.spliterator();
621 >                do {} while (s.tryAdvance(checkSanity));
622 >            },
623 >            () -> { for (Object x : c) checkSanity.accept(x); },
624 >            () -> checkArraySanity.accept(c.toArray()),
625 >            () -> checkArraySanity.accept(c.toArray(emptyArray)),
626 >            () -> {
627 >                Object[] a = new Object[5];
628 >                Object three = impl.makeElement(3);
629 >                Arrays.fill(a, 0, a.length, three);
630 >                Object[] x = c.toArray(a);
631 >                if (x == a)
632 >                    for (int i = 0; i < a.length && a[i] != null; i++)
633 >                        checkSanity.accept(a[i]);
634 >                    // A careful reading of the spec does not support:
635 >                    // for (i++; i < a.length; i++) assertSame(three, a[i]);
636 >                else
637 >                    checkArraySanity.accept(x);
638 >                },
639 >            adderRemover(c, one),
640 >            adderRemover(c, two),
641 >        };
642 >        final List<Runnable> tasks =
643 >            Arrays.stream(frobbers)
644 >            .filter(task -> rnd.nextBoolean()) // random subset
645 >            .map(task -> (Runnable) () -> {
646 >                     threadsStarted.arriveAndAwaitAdvance();
647 >                     while (!done.get())
648 >                         task.run();
649 >                 })
650 >            .collect(Collectors.toList());
651          final ExecutorService pool = Executors.newCachedThreadPool();
652          try (PoolCleaner cleaner = cleaner(pool, done)) {
653 <            final CountDownLatch threadsStarted = new CountDownLatch(2);
654 <            Runnable checkElt = () -> {
655 <                threadsStarted.countDown();
656 <                while (!done.get())
657 <                    c.forEach((x) -> { assertSame(x, elt); }); };
392 <            Runnable addRemove = () -> {
393 <                threadsStarted.countDown();
394 <                while (!done.get()) {
395 <                    assertTrue(c.add(elt));
396 <                    assertTrue(c.remove(elt));
397 <                }};
398 <            f1 = pool.submit(checkElt);
399 <            f2 = pool.submit(addRemove);
653 >            threadsStarted.bulkRegister(tasks.size());
654 >            futures = tasks.stream()
655 >                .map(pool::submit)
656 >                .collect(Collectors.toList());
657 >            threadsStarted.arriveAndDeregister();
658              Thread.sleep(testDurationMillis);
659          }
660 <        assertNull(f1.get(0L, MILLISECONDS));
661 <        assertNull(f2.get(0L, MILLISECONDS));
660 >        for (Future future : futures)
661 >            assertNull(future.get(0L, MILLISECONDS));
662 >    }
663 >
664 >    /**
665 >     * Spliterators are either IMMUTABLE or truly late-binding or, if
666 >     * concurrent, use the same "late-binding style" of returning
667 >     * elements added between creation and first use.
668 >     */
669 >    public void testLateBindingStyle() {
670 >        if (!testImplementationDetails) return;
671 >        if (impl.klazz() == ArrayList.class) return; // for jdk8
672 >        // Immutable (snapshot) spliterators are exempt
673 >        if (impl.emptyCollection().spliterator()
674 >            .hasCharacteristics(Spliterator.IMMUTABLE))
675 >            return;
676 >        final Object one = impl.makeElement(1);
677 >        {
678 >            final Collection c = impl.emptyCollection();
679 >            final Spliterator split = c.spliterator();
680 >            c.add(one);
681 >            assertTrue(split.tryAdvance(e -> { assertSame(e, one); }));
682 >            assertFalse(split.tryAdvance(e -> { throw new AssertionError(); }));
683 >            assertTrue(c.contains(one));
684 >        }
685 >        {
686 >            final AtomicLong count = new AtomicLong(0);
687 >            final Collection c = impl.emptyCollection();
688 >            final Spliterator split = c.spliterator();
689 >            c.add(one);
690 >            split.forEachRemaining(
691 >                e -> { assertSame(e, one); count.getAndIncrement(); });
692 >            assertEquals(1L, count.get());
693 >            assertFalse(split.tryAdvance(e -> { throw new AssertionError(); }));
694 >            assertTrue(c.contains(one));
695 >        }
696      }
697  
698   //     public void testCollection8DebugFail() {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines