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.12 by jsr166, Sat Nov 5 16:10:38 2016 UTC

# Line 10 | Line 10 | import static java.util.concurrent.TimeU
10   import java.util.ArrayList;
11   import java.util.Collection;
12   import java.util.Collections;
13 + import java.util.Deque;
14 + import java.util.HashSet;
15 + import java.util.Iterator;
16 + import java.util.List;
17 + import java.util.NoSuchElementException;
18 + import java.util.Queue;
19 + import java.util.Spliterator;
20 + import java.util.concurrent.CountDownLatch;
21   import java.util.concurrent.Executors;
22   import java.util.concurrent.ExecutorService;
23   import java.util.concurrent.Future;
24 + import java.util.concurrent.ThreadLocalRandom;
25   import java.util.concurrent.atomic.AtomicBoolean;
26   import java.util.concurrent.atomic.AtomicLong;
27 + import java.util.concurrent.atomic.AtomicReference;
28   import java.util.function.Consumer;
29 + import java.util.function.Predicate;
30  
31   import junit.framework.Test;
32  
# Line 38 | Line 49 | public class Collection8Test extends JSR
49                                        impl);
50      }
51  
52 +    Object bomb() {
53 +        return new Object() {
54 +                public boolean equals(Object x) { throw new AssertionError(); }
55 +                public int hashCode() { throw new AssertionError(); }
56 +            };
57 +    }
58 +
59 +    /** Checks properties of empty collections. */
60 +    public void testEmptyMeansEmpty() {
61 +        Collection c = impl.emptyCollection();
62 +        emptyMeansEmpty(c);
63 +
64 +        if (c instanceof java.io.Serializable)
65 +            emptyMeansEmpty(serialClone(c));
66 +
67 +        Collection clone = cloneableClone(c);
68 +        if (clone != null)
69 +            emptyMeansEmpty(clone);
70 +    }
71 +
72 +    void emptyMeansEmpty(Collection c) {
73 +        assertTrue(c.isEmpty());
74 +        assertEquals(0, c.size());
75 +        assertEquals("[]", c.toString());
76 +        {
77 +            Object[] a = c.toArray();
78 +            assertEquals(0, a.length);
79 +            assertSame(Object[].class, a.getClass());
80 +        }
81 +        {
82 +            Object[] a = new Object[0];
83 +            assertSame(a, c.toArray(a));
84 +        }
85 +        {
86 +            Integer[] a = new Integer[0];
87 +            assertSame(a, c.toArray(a));
88 +        }
89 +        {
90 +            Integer[] a = { 1, 2, 3};
91 +            assertSame(a, c.toArray(a));
92 +            assertNull(a[0]);
93 +            assertSame(2, a[1]);
94 +            assertSame(3, a[2]);
95 +        }
96 +        assertIteratorExhausted(c.iterator());
97 +        Consumer alwaysThrows = (e) -> { throw new AssertionError(); };
98 +        c.forEach(alwaysThrows);
99 +        c.iterator().forEachRemaining(alwaysThrows);
100 +        c.spliterator().forEachRemaining(alwaysThrows);
101 +        assertFalse(c.spliterator().tryAdvance(alwaysThrows));
102 +        if (c.spliterator().hasCharacteristics(Spliterator.SIZED))
103 +            assertEquals(0, c.spliterator().estimateSize());
104 +        assertFalse(c.contains(bomb()));
105 +        assertFalse(c.remove(bomb()));
106 +        if (c instanceof Queue) {
107 +            Queue q = (Queue) c;
108 +            assertNull(q.peek());
109 +            assertNull(q.poll());
110 +        }
111 +        if (c instanceof Deque) {
112 +            Deque d = (Deque) c;
113 +            assertNull(d.peekFirst());
114 +            assertNull(d.peekLast());
115 +            assertNull(d.pollFirst());
116 +            assertNull(d.pollLast());
117 +            assertIteratorExhausted(d.descendingIterator());
118 +            d.descendingIterator().forEachRemaining(alwaysThrows);
119 +            assertFalse(d.removeFirstOccurrence(bomb()));
120 +            assertFalse(d.removeLastOccurrence(bomb()));
121 +        }
122 +    }
123 +
124 +    public void testNullPointerExceptions() {
125 +        Collection c = impl.emptyCollection();
126 +        assertThrows(
127 +            NullPointerException.class,
128 +            () -> c.addAll(null),
129 +            () -> c.containsAll(null),
130 +            () -> c.retainAll(null),
131 +            () -> c.removeAll(null),
132 +            () -> c.removeIf(null),
133 +            () -> c.forEach(null),
134 +            () -> c.iterator().forEachRemaining(null),
135 +            () -> c.spliterator().forEachRemaining(null),
136 +            () -> c.spliterator().tryAdvance(null),
137 +            () -> c.toArray(null));
138 +
139 +        if (!impl.permitsNulls()) {
140 +            assertThrows(
141 +                NullPointerException.class,
142 +                () -> c.add(null));
143 +        }
144 +        if (!impl.permitsNulls()
145 +            && Queue.class.isAssignableFrom(impl.klazz())) {
146 +            Queue q = (Queue) c;
147 +            assertThrows(
148 +                NullPointerException.class,
149 +                () -> q.offer(null));
150 +        }
151 +        if (!impl.permitsNulls()
152 +            && Deque.class.isAssignableFrom(impl.klazz())) {
153 +            Deque d = (Deque) c;
154 +            assertThrows(
155 +                NullPointerException.class,
156 +                () -> d.addFirst(null),
157 +                () -> d.addLast(null),
158 +                () -> d.offerFirst(null),
159 +                () -> d.offerLast(null),
160 +                () -> d.push(null),
161 +                () -> d.descendingIterator().forEachRemaining(null));
162 +        }
163 +    }
164 +
165 +    public void testNoSuchElementExceptions() {
166 +        Collection c = impl.emptyCollection();
167 +        assertThrows(
168 +            NoSuchElementException.class,
169 +            () -> c.iterator().next());
170 +
171 +        if (Queue.class.isAssignableFrom(impl.klazz())) {
172 +            Queue q = (Queue) c;
173 +            assertThrows(
174 +                NoSuchElementException.class,
175 +                () -> q.element(),
176 +                () -> q.remove());
177 +        }
178 +        if (Deque.class.isAssignableFrom(impl.klazz())) {
179 +            Deque d = (Deque) c;
180 +            assertThrows(
181 +                NoSuchElementException.class,
182 +                () -> d.getFirst(),
183 +                () -> d.getLast(),
184 +                () -> d.removeFirst(),
185 +                () -> d.removeLast(),
186 +                () -> d.pop(),
187 +                () -> d.descendingIterator().next());
188 +        }
189 +    }
190 +
191 +    public void testRemoveIf() {
192 +        Collection c = impl.emptyCollection();
193 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
194 +        int n = rnd.nextInt(6);
195 +        for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
196 +        AtomicReference threwAt = new AtomicReference(null);
197 +        ArrayList survivors = new ArrayList(c);
198 +        ArrayList accepts = new ArrayList();
199 +        ArrayList rejects = new ArrayList();
200 +        Predicate randomPredicate = (e) -> {
201 +            assertNull(threwAt.get());
202 +            switch (rnd.nextInt(3)) {
203 +            case 0: accepts.add(e); return true;
204 +            case 1: rejects.add(e); return false;
205 +            case 2: threwAt.set(e); throw new ArithmeticException();
206 +            default: throw new AssertionError();
207 +            }
208 +        };
209 +        try {
210 +            assertFalse(survivors.contains(null));
211 +            try {
212 +                boolean modified = c.removeIf(randomPredicate);
213 +                if (!modified) {
214 +                    assertNull(threwAt.get());
215 +                    assertEquals(n, rejects.size());
216 +                    assertEquals(0, accepts.size());
217 +                }
218 +            } catch (ArithmeticException ok) {}
219 +            survivors.removeAll(accepts);
220 +            assertEquals(n - accepts.size(), c.size());
221 +            assertTrue(c.containsAll(survivors));
222 +            assertTrue(survivors.containsAll(rejects));
223 +            for (Object x : accepts) assertFalse(c.contains(x));
224 +            if (threwAt.get() == null)
225 +                assertEquals(accepts.size() + rejects.size(), n);
226 +        } catch (Throwable ex) {
227 +            System.err.println(impl.klazz());
228 +            System.err.printf("c=%s%n", c);
229 +            System.err.printf("n=%d%n", n);
230 +            System.err.printf("accepts=%s%n", accepts);
231 +            System.err.printf("rejects=%s%n", rejects);
232 +            System.err.printf("survivors=%s%n", survivors);
233 +            System.err.printf("threw=%s%n", threwAt.get());
234 +            throw ex;
235 +        }
236 +    }
237 +
238 +    /**
239 +     * Various ways of traversing a collection yield same elements
240 +     */
241 +    public void testIteratorEquivalence() {
242 +        Collection c = impl.emptyCollection();
243 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
244 +        int n = rnd.nextInt(6);
245 +        for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
246 +        ArrayList iterated = new ArrayList();
247 +        ArrayList iteratedForEachRemaining = new ArrayList();
248 +        ArrayList spliterated = new ArrayList();
249 +        ArrayList foreached = new ArrayList();
250 +        for (Object x : c) iterated.add(x);
251 +        c.iterator().forEachRemaining(e -> iteratedForEachRemaining.add(e));
252 +        c.spliterator().forEachRemaining(e -> spliterated.add(e));
253 +        c.forEach(e -> foreached.add(e));
254 +        boolean ordered =
255 +            c.spliterator().hasCharacteristics(Spliterator.ORDERED);
256 +        if (c instanceof List || c instanceof Deque)
257 +            assertTrue(ordered);
258 +        if (ordered) {
259 +            assertEquals(iterated, iteratedForEachRemaining);
260 +            assertEquals(iterated, spliterated);
261 +            assertEquals(iterated, foreached);
262 +        } else {
263 +            HashSet cset = new HashSet(c);
264 +            assertEquals(cset, new HashSet(iterated));
265 +            assertEquals(cset, new HashSet(iteratedForEachRemaining));
266 +            assertEquals(cset, new HashSet(spliterated));
267 +            assertEquals(cset, new HashSet(foreached));
268 +        }
269 +        if (c instanceof Deque) {
270 +            Deque d = (Deque) c;
271 +            ArrayList descending = new ArrayList();
272 +            ArrayList descendingForEachRemaining = new ArrayList();
273 +            for (Iterator it = d.descendingIterator(); it.hasNext(); )
274 +                descending.add(it.next());
275 +            d.descendingIterator().forEachRemaining(
276 +                e -> descendingForEachRemaining.add(e));
277 +            Collections.reverse(descending);
278 +            Collections.reverse(descendingForEachRemaining);
279 +            assertEquals(iterated, descending);
280 +            assertEquals(iterated, descendingForEachRemaining);
281 +        }
282 +    }
283 +
284 +    /**
285 +     * Calling Iterator#remove() after Iterator#forEachRemaining
286 +     * should remove last element
287 +     */
288 +    public void testRemoveAfterForEachRemaining() {
289 +        Collection c = impl.emptyCollection();
290 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
291 +        {
292 +            int n = 3 + rnd.nextInt(2);
293 +            for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
294 +            Iterator it = c.iterator();
295 +            assertTrue(it.hasNext());
296 +            assertEquals(impl.makeElement(0), it.next());
297 +            assertTrue(it.hasNext());
298 +            assertEquals(impl.makeElement(1), it.next());
299 +            it.forEachRemaining((e) -> {});
300 +            it.remove();
301 +            assertEquals(n - 1, c.size());
302 +            for (int i = 0; i < n - 1; i++)
303 +                assertTrue(c.contains(impl.makeElement(i)));
304 +            assertFalse(c.contains(impl.makeElement(n - 1)));
305 +        }
306 +        if (c instanceof Deque) {
307 +            Deque d = (Deque) impl.emptyCollection();
308 +            int n = 3 + rnd.nextInt(2);
309 +            for (int i = 0; i < n; i++) d.add(impl.makeElement(i));
310 +            Iterator it = d.descendingIterator();
311 +            assertTrue(it.hasNext());
312 +            assertEquals(impl.makeElement(n - 1), it.next());
313 +            assertTrue(it.hasNext());
314 +            assertEquals(impl.makeElement(n - 2), it.next());
315 +            it.forEachRemaining((e) -> {});
316 +            it.remove();
317 +            assertEquals(n - 1, d.size());
318 +            for (int i = 1; i < n; i++)
319 +                assertTrue(d.contains(impl.makeElement(i)));
320 +            assertFalse(d.contains(impl.makeElement(0)));
321 +        }
322 +    }
323 +
324      /**
325       * stream().forEach returns elements in the collection
326       */
327 <    public void testForEach() throws Throwable {
327 >    public void testStreamForEach() throws Throwable {
328          final Collection c = impl.emptyCollection();
329          final AtomicLong count = new AtomicLong(0L);
330          final Object x = impl.makeElement(1);
# Line 68 | Line 351 | public class Collection8Test extends JSR
351          assertTrue(found.isEmpty());
352      }
353  
354 +    public void testStreamForEachConcurrentStressTest() throws Throwable {
355 +        if (!impl.isConcurrent()) return;
356 +        final Collection c = impl.emptyCollection();
357 +        final long testDurationMillis = timeoutMillis();
358 +        final AtomicBoolean done = new AtomicBoolean(false);
359 +        final Object elt = impl.makeElement(1);
360 +        final Future<?> f1, f2;
361 +        final ExecutorService pool = Executors.newCachedThreadPool();
362 +        try (PoolCleaner cleaner = cleaner(pool, done)) {
363 +            final CountDownLatch threadsStarted = new CountDownLatch(2);
364 +            Runnable checkElt = () -> {
365 +                threadsStarted.countDown();
366 +                while (!done.get())
367 +                    c.stream().forEach((x) -> { assertSame(x, elt); }); };
368 +            Runnable addRemove = () -> {
369 +                threadsStarted.countDown();
370 +                while (!done.get()) {
371 +                    assertTrue(c.add(elt));
372 +                    assertTrue(c.remove(elt));
373 +                }};
374 +            f1 = pool.submit(checkElt);
375 +            f2 = pool.submit(addRemove);
376 +            Thread.sleep(testDurationMillis);
377 +        }
378 +        assertNull(f1.get(0L, MILLISECONDS));
379 +        assertNull(f2.get(0L, MILLISECONDS));
380 +    }
381 +
382 +    /**
383 +     * collection.forEach returns elements in the collection
384 +     */
385 +    public void testForEach() throws Throwable {
386 +        final Collection c = impl.emptyCollection();
387 +        final AtomicLong count = new AtomicLong(0L);
388 +        final Object x = impl.makeElement(1);
389 +        final Object y = impl.makeElement(2);
390 +        final ArrayList found = new ArrayList();
391 +        Consumer<Object> spy = (o) -> { found.add(o); };
392 +        c.forEach(spy);
393 +        assertTrue(found.isEmpty());
394 +
395 +        assertTrue(c.add(x));
396 +        c.forEach(spy);
397 +        assertEquals(Collections.singletonList(x), found);
398 +        found.clear();
399 +
400 +        assertTrue(c.add(y));
401 +        c.forEach(spy);
402 +        assertEquals(2, found.size());
403 +        assertTrue(found.contains(x));
404 +        assertTrue(found.contains(y));
405 +        found.clear();
406 +
407 +        c.clear();
408 +        c.forEach(spy);
409 +        assertTrue(found.isEmpty());
410 +    }
411 +
412      public void testForEachConcurrentStressTest() throws Throwable {
413          if (!impl.isConcurrent()) return;
414          final Collection c = impl.emptyCollection();
415 <        final long testDurationMillis = SHORT_DELAY_MS;
415 >        final long testDurationMillis = timeoutMillis();
416          final AtomicBoolean done = new AtomicBoolean(false);
417          final Object elt = impl.makeElement(1);
418 <        ExecutorService pool = Executors.newCachedThreadPool();
419 <        Runnable checkElt = () -> {
420 <            while (!done.get())
421 <                c.stream().forEach((x) -> { assertSame(x, elt); }); };
422 <        Runnable addRemove = () -> {
423 <            while (!done.get()) {
424 <                assertTrue(c.add(elt));
425 <                assertTrue(c.remove(elt));
426 <            }};
427 <        Future<?> f1 = pool.submit(checkElt);
428 <        Future<?> f2 = pool.submit(addRemove);
429 <        Thread.sleep(testDurationMillis);
430 <        done.set(true);
431 <        pool.shutdown();
432 <        assertTrue(pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
433 <        assertNull(f1.get(LONG_DELAY_MS, MILLISECONDS));
434 <        assertNull(f2.get(LONG_DELAY_MS, MILLISECONDS));
418 >        final Future<?> f1, f2;
419 >        final ExecutorService pool = Executors.newCachedThreadPool();
420 >        try (PoolCleaner cleaner = cleaner(pool, done)) {
421 >            final CountDownLatch threadsStarted = new CountDownLatch(2);
422 >            Runnable checkElt = () -> {
423 >                threadsStarted.countDown();
424 >                while (!done.get())
425 >                    c.forEach((x) -> { assertSame(x, elt); }); };
426 >            Runnable addRemove = () -> {
427 >                threadsStarted.countDown();
428 >                while (!done.get()) {
429 >                    assertTrue(c.add(elt));
430 >                    assertTrue(c.remove(elt));
431 >                }};
432 >            f1 = pool.submit(checkElt);
433 >            f2 = pool.submit(addRemove);
434 >            Thread.sleep(testDurationMillis);
435 >        }
436 >        assertNull(f1.get(0L, MILLISECONDS));
437 >        assertNull(f2.get(0L, MILLISECONDS));
438      }
439  
440 <    // public void testCollection8DebugFail() { fail(); }
440 > //     public void testCollection8DebugFail() {
441 > //         fail(impl.klazz().getSimpleName());
442 > //     }
443   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines