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.1 by jsr166, Sun Jun 14 20:58:14 2015 UTC vs.
Revision 1.23 by jsr166, Mon Nov 14 21:33:58 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;
16 + import java.util.HashSet;
17 + import java.util.Iterator;
18 + import java.util.List;
19 + import java.util.NoSuchElementException;
20 + import java.util.Queue;
21 + import java.util.Spliterator;
22 + import java.util.concurrent.BlockingDeque;
23 + import java.util.concurrent.BlockingQueue;
24 + import java.util.concurrent.CountDownLatch;
25   import java.util.concurrent.Executors;
26   import java.util.concurrent.ExecutorService;
27   import java.util.concurrent.Future;
28 + import java.util.concurrent.ThreadLocalRandom;
29   import java.util.concurrent.atomic.AtomicBoolean;
30   import java.util.concurrent.atomic.AtomicLong;
31 + import java.util.concurrent.atomic.AtomicReference;
32   import java.util.function.Consumer;
33 + import java.util.function.Predicate;
34  
35   import junit.framework.Test;
36  
# Line 38 | Line 53 | public class Collection8Test extends JSR
53                                        impl);
54      }
55  
56 +    Object bomb() {
57 +        return new Object() {
58 +                public boolean equals(Object x) { throw new AssertionError(); }
59 +                public int hashCode() { throw new AssertionError(); }
60 +            };
61 +    }
62 +
63 +    /** Checks properties of empty collections. */
64 +    public void testEmptyMeansEmpty() throws InterruptedException {
65 +        Collection c = impl.emptyCollection();
66 +        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 +    void emptyMeansEmpty(Collection c) throws InterruptedException {
77 +        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 +        Consumer alwaysThrows = e -> { throw new AssertionError(); };
102 +        c.forEach(alwaysThrows);
103 +        c.iterator().forEachRemaining(alwaysThrows);
104 +        c.spliterator().forEachRemaining(alwaysThrows);
105 +        assertFalse(c.spliterator().tryAdvance(alwaysThrows));
106 +        if (c.spliterator().hasCharacteristics(Spliterator.SIZED))
107 +            assertEquals(0, c.spliterator().estimateSize());
108 +        assertFalse(c.contains(bomb()));
109 +        assertFalse(c.remove(bomb()));
110 +        if (c instanceof Queue) {
111 +            Queue q = (Queue) c;
112 +            assertNull(q.peek());
113 +            assertNull(q.poll());
114 +        }
115 +        if (c instanceof Deque) {
116 +            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 +            d.descendingIterator().forEachRemaining(alwaysThrows);
123 +            assertFalse(d.removeFirstOccurrence(bomb()));
124 +            assertFalse(d.removeLastOccurrence(bomb()));
125 +        }
126 +        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 +    }
136 +
137 +    public void testNullPointerExceptions() throws InterruptedException {
138 +        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 +            () -> c.forEach(null),
147 +            () -> c.iterator().forEachRemaining(null),
148 +            () -> c.spliterator().forEachRemaining(null),
149 +            () -> c.spliterator().tryAdvance(null),
150 +            () -> c.toArray(null));
151 +
152 +        if (!impl.permitsNulls()) {
153 +            assertThrows(
154 +                NullPointerException.class,
155 +                () -> c.add(null));
156 +        }
157 +        if (!impl.permitsNulls() && c instanceof Queue) {
158 +            Queue q = (Queue) c;
159 +            assertThrows(
160 +                NullPointerException.class,
161 +                () -> q.offer(null));
162 +        }
163 +        if (!impl.permitsNulls() && c instanceof Deque) {
164 +            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 +                () -> d.push(null),
172 +                () -> d.descendingIterator().forEachRemaining(null));
173 +        }
174 +        if (c instanceof BlockingQueue) {
175 +            BlockingQueue q = (BlockingQueue) c;
176 +            assertThrows(
177 +                NullPointerException.class,
178 +                () -> {
179 +                    try { q.offer(null, 1L, HOURS); }
180 +                    catch (InterruptedException ex) {
181 +                        throw new AssertionError(ex);
182 +                    }},
183 +                () -> {
184 +                    try { q.put(null); }
185 +                    catch (InterruptedException ex) {
186 +                        throw new AssertionError(ex);
187 +                    }});
188 +        }
189 +        if (c instanceof BlockingDeque) {
190 +            BlockingDeque q = (BlockingDeque) c;
191 +            assertThrows(
192 +                NullPointerException.class,
193 +                () -> {
194 +                    try { q.offerFirst(null, 1L, HOURS); }
195 +                    catch (InterruptedException ex) {
196 +                        throw new AssertionError(ex);
197 +                    }},
198 +                () -> {
199 +                    try { q.offerLast(null, 1L, HOURS); }
200 +                    catch (InterruptedException ex) {
201 +                        throw new AssertionError(ex);
202 +                    }},
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 +                    }});
213 +        }
214 +    }
215 +
216 +    public void testNoSuchElementExceptions() {
217 +        Collection c = impl.emptyCollection();
218 +        assertThrows(
219 +            NoSuchElementException.class,
220 +            () -> c.iterator().next());
221 +
222 +        if (c instanceof Queue) {
223 +            Queue q = (Queue) c;
224 +            assertThrows(
225 +                NoSuchElementException.class,
226 +                () -> q.element(),
227 +                () -> q.remove());
228 +        }
229 +        if (c instanceof Deque) {
230 +            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 +        boolean ordered =
245 +            c.spliterator().hasCharacteristics(Spliterator.ORDERED);
246 +        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 +        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 +        ArrayList accepts = new ArrayList();
259 +        ArrayList rejects = new ArrayList();
260 +
261 +        Predicate randomPredicate = e -> {
262 +            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 +            try {
272 +                boolean modified = c.removeIf(randomPredicate);
273 +                assertNull(threwAt.get());
274 +                assertEquals(modified, accepts.size() > 0);
275 +                assertEquals(modified, rejects.size() != n);
276 +                assertEquals(accepts.size() + rejects.size(), n);
277 +                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 +            } 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 +            assertTrue(c.containsAll(survivors));
303 +            assertTrue(survivors.containsAll(rejects));
304 +            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 +        } catch (Throwable ex) {
316 +            System.err.println(impl.klazz());
317 +            // c is at risk of corruption if we got here, so be lenient
318 +            try { System.err.printf("c=%s%n", c); }
319 +            catch (Throwable t) { t.printStackTrace(); }
320 +            System.err.printf("n=%d%n", n);
321 +            System.err.printf("orig=%s%n", orig);
322 +            System.err.printf("accepts=%s%n", accepts);
323 +            System.err.printf("rejects=%s%n", rejects);
324 +            System.err.printf("survivors=%s%n", survivors);
325 +            System.err.printf("threwAt=%s%n", threwAt.get());
326 +            throw ex;
327 +        }
328 +    }
329 +
330 +    /**
331 +     * Various ways of traversing a collection yield same elements
332 +     */
333 +    public void testIteratorEquivalence() {
334 +        Collection c = impl.emptyCollection();
335 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
336 +        int n = rnd.nextInt(6);
337 +        for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
338 +        ArrayList iterated = new ArrayList();
339 +        ArrayList iteratedForEachRemaining = new ArrayList();
340 +        ArrayList tryAdvanced = new ArrayList();
341 +        ArrayList spliterated = new ArrayList();
342 +        ArrayList forEached = new ArrayList();
343 +        ArrayList removeIfed = new ArrayList();
344 +        for (Object x : c) iterated.add(x);
345 +        c.iterator().forEachRemaining(e -> iteratedForEachRemaining.add(e));
346 +        for (Spliterator s = c.spliterator();
347 +             s.tryAdvance(e -> tryAdvanced.add(e)); ) {}
348 +        c.spliterator().forEachRemaining(e -> spliterated.add(e));
349 +        c.forEach(e -> forEached.add(e));
350 +        c.removeIf(e -> { removeIfed.add(e); return false; });
351 +        boolean ordered =
352 +            c.spliterator().hasCharacteristics(Spliterator.ORDERED);
353 +        if (c instanceof List || c instanceof Deque)
354 +            assertTrue(ordered);
355 +        if (ordered) {
356 +            assertEquals(iterated, iteratedForEachRemaining);
357 +            assertEquals(iterated, tryAdvanced);
358 +            assertEquals(iterated, spliterated);
359 +            assertEquals(iterated, forEached);
360 +            assertEquals(iterated, removeIfed);
361 +        } else {
362 +            HashSet cset = new HashSet(c);
363 +            assertEquals(cset, new HashSet(iterated));
364 +            assertEquals(cset, new HashSet(iteratedForEachRemaining));
365 +            assertEquals(cset, new HashSet(tryAdvanced));
366 +            assertEquals(cset, new HashSet(spliterated));
367 +            assertEquals(cset, new HashSet(forEached));
368 +            assertEquals(cset, new HashSet(removeIfed));
369 +        }
370 +        if (c instanceof Deque) {
371 +            Deque d = (Deque) c;
372 +            ArrayList descending = new ArrayList();
373 +            ArrayList descendingForEachRemaining = new ArrayList();
374 +            for (Iterator it = d.descendingIterator(); it.hasNext(); )
375 +                descending.add(it.next());
376 +            d.descendingIterator().forEachRemaining(
377 +                e -> descendingForEachRemaining.add(e));
378 +            Collections.reverse(descending);
379 +            Collections.reverse(descendingForEachRemaining);
380 +            assertEquals(iterated, descending);
381 +            assertEquals(iterated, descendingForEachRemaining);
382 +        }
383 +    }
384 +
385 +    /**
386 +     * Calling Iterator#remove() after Iterator#forEachRemaining
387 +     * should (maybe) remove last element
388 +     */
389 +    public void testRemoveAfterForEachRemaining() {
390 +        Collection c = impl.emptyCollection();
391 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
392 +        {
393 +            int n = 3 + rnd.nextInt(2);
394 +            for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
395 +            Iterator it = c.iterator();
396 +            assertTrue(it.hasNext());
397 +            assertEquals(impl.makeElement(0), it.next());
398 +            assertTrue(it.hasNext());
399 +            assertEquals(impl.makeElement(1), it.next());
400 +            it.forEachRemaining(e -> assertTrue(c.contains(e)));
401 +            if (testImplementationDetails) {
402 +                if (c instanceof java.util.concurrent.ArrayBlockingQueue) {
403 +                    assertIteratorExhausted(it);
404 +                } else {
405 +                    it.remove();
406 +                    assertEquals(n - 1, c.size());
407 +                    for (int i = 0; i < n - 1; i++)
408 +                        assertTrue(c.contains(impl.makeElement(i)));
409 +                    assertFalse(c.contains(impl.makeElement(n - 1)));
410 +                }
411 +            }
412 +        }
413 +        if (c instanceof Deque) {
414 +            Deque d = (Deque) impl.emptyCollection();
415 +            int n = 3 + rnd.nextInt(2);
416 +            for (int i = 0; i < n; i++) d.add(impl.makeElement(i));
417 +            Iterator it = d.descendingIterator();
418 +            assertTrue(it.hasNext());
419 +            assertEquals(impl.makeElement(n - 1), it.next());
420 +            assertTrue(it.hasNext());
421 +            assertEquals(impl.makeElement(n - 2), it.next());
422 +            it.forEachRemaining(e -> assertTrue(c.contains(e)));
423 +            if (testImplementationDetails) {
424 +                it.remove();
425 +                assertEquals(n - 1, d.size());
426 +                for (int i = 1; i < n; i++)
427 +                    assertTrue(d.contains(impl.makeElement(i)));
428 +                assertFalse(d.contains(impl.makeElement(0)));
429 +            }
430 +        }
431 +    }
432 +
433      /**
434       * stream().forEach returns elements in the collection
435       */
436 <    public void testForEach() throws Throwable {
436 >    public void testStreamForEach() throws Throwable {
437          final Collection c = impl.emptyCollection();
438          final AtomicLong count = new AtomicLong(0L);
439          final Object x = impl.makeElement(1);
440          final Object y = impl.makeElement(2);
441          final ArrayList found = new ArrayList();
442 <        Consumer<Object> spy = (o) -> { found.add(o); };
442 >        Consumer<Object> spy = o -> found.add(o);
443          c.stream().forEach(spy);
444          assertTrue(found.isEmpty());
445  
# Line 68 | Line 460 | public class Collection8Test extends JSR
460          assertTrue(found.isEmpty());
461      }
462  
463 +    public void testStreamForEachConcurrentStressTest() throws Throwable {
464 +        if (!impl.isConcurrent()) return;
465 +        final Collection c = impl.emptyCollection();
466 +        final long testDurationMillis = timeoutMillis();
467 +        final AtomicBoolean done = new AtomicBoolean(false);
468 +        final Object elt = impl.makeElement(1);
469 +        final Future<?> f1, f2;
470 +        final ExecutorService pool = Executors.newCachedThreadPool();
471 +        try (PoolCleaner cleaner = cleaner(pool, done)) {
472 +            final CountDownLatch threadsStarted = new CountDownLatch(2);
473 +            Runnable checkElt = () -> {
474 +                threadsStarted.countDown();
475 +                while (!done.get())
476 +                    c.stream().forEach(x -> assertSame(x, elt)); };
477 +            Runnable addRemove = () -> {
478 +                threadsStarted.countDown();
479 +                while (!done.get()) {
480 +                    assertTrue(c.add(elt));
481 +                    assertTrue(c.remove(elt));
482 +                }};
483 +            f1 = pool.submit(checkElt);
484 +            f2 = pool.submit(addRemove);
485 +            Thread.sleep(testDurationMillis);
486 +        }
487 +        assertNull(f1.get(0L, MILLISECONDS));
488 +        assertNull(f2.get(0L, MILLISECONDS));
489 +    }
490 +
491 +    /**
492 +     * collection.forEach returns elements in the collection
493 +     */
494 +    public void testForEach() throws Throwable {
495 +        final Collection c = impl.emptyCollection();
496 +        final AtomicLong count = new AtomicLong(0L);
497 +        final Object x = impl.makeElement(1);
498 +        final Object y = impl.makeElement(2);
499 +        final ArrayList found = new ArrayList();
500 +        Consumer<Object> spy = o -> found.add(o);
501 +        c.forEach(spy);
502 +        assertTrue(found.isEmpty());
503 +
504 +        assertTrue(c.add(x));
505 +        c.forEach(spy);
506 +        assertEquals(Collections.singletonList(x), found);
507 +        found.clear();
508 +
509 +        assertTrue(c.add(y));
510 +        c.forEach(spy);
511 +        assertEquals(2, found.size());
512 +        assertTrue(found.contains(x));
513 +        assertTrue(found.contains(y));
514 +        found.clear();
515 +
516 +        c.clear();
517 +        c.forEach(spy);
518 +        assertTrue(found.isEmpty());
519 +    }
520 +
521      public void testForEachConcurrentStressTest() throws Throwable {
522          if (!impl.isConcurrent()) return;
523          final Collection c = impl.emptyCollection();
524 <        final long testDurationMillis = SHORT_DELAY_MS;
524 >        final long testDurationMillis = timeoutMillis();
525          final AtomicBoolean done = new AtomicBoolean(false);
526          final Object elt = impl.makeElement(1);
527 <        ExecutorService pool = Executors.newCachedThreadPool();
528 <        Runnable checkElt = () -> {
529 <            while (!done.get())
530 <                c.stream().forEach((x) -> { assertSame(x, elt); }); };
531 <        Runnable addRemove = () -> {
532 <            while (!done.get()) {
533 <                assertTrue(c.add(elt));
534 <                assertTrue(c.remove(elt));
535 <            }};
536 <        Future<?> f1 = pool.submit(checkElt);
537 <        Future<?> f2 = pool.submit(addRemove);
538 <        Thread.sleep(testDurationMillis);
539 <        done.set(true);
540 <        pool.shutdown();
541 <        assertTrue(pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
542 <        assertNull(f1.get(LONG_DELAY_MS, MILLISECONDS));
543 <        assertNull(f2.get(LONG_DELAY_MS, MILLISECONDS));
527 >        final Future<?> f1, f2;
528 >        final ExecutorService pool = Executors.newCachedThreadPool();
529 >        try (PoolCleaner cleaner = cleaner(pool, done)) {
530 >            final CountDownLatch threadsStarted = new CountDownLatch(2);
531 >            Runnable checkElt = () -> {
532 >                threadsStarted.countDown();
533 >                while (!done.get())
534 >                    c.forEach(x -> assertSame(x, elt)); };
535 >            Runnable addRemove = () -> {
536 >                threadsStarted.countDown();
537 >                while (!done.get()) {
538 >                    assertTrue(c.add(elt));
539 >                    assertTrue(c.remove(elt));
540 >                }};
541 >            f1 = pool.submit(checkElt);
542 >            f2 = pool.submit(addRemove);
543 >            Thread.sleep(testDurationMillis);
544 >        }
545 >        assertNull(f1.get(0L, MILLISECONDS));
546 >        assertNull(f2.get(0L, MILLISECONDS));
547      }
548  
549 <    // public void testCollection8DebugFail() { fail(); }
549 > //     public void testCollection8DebugFail() {
550 > //         fail(impl.klazz().getSimpleName());
551 > //     }
552   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines