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.11 by jsr166, Sat Nov 5 05:09:57 2016 UTC vs.
Revision 1.25 by jsr166, Tue Nov 15 00:08:25 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.CountDownLatch;
25   import java.util.concurrent.Executors;
26   import java.util.concurrent.ExecutorService;
# Line 57 | Line 61 | public class Collection8Test extends JSR
61      }
62  
63      /** Checks properties of empty collections. */
64 <    public void testEmptyMeansEmpty() {
64 >    public void testEmptyMeansEmpty() throws Throwable {
65          Collection c = impl.emptyCollection();
66 +        emptyMeansEmpty(c);
67 +
68 +        if (c instanceof java.io.Serializable) {
69 +            try {
70 +                emptyMeansEmpty(serialClonePossiblyFailing(c));
71 +            } catch (java.io.NotSerializableException ex) {
72 +                // excusable when we have a serializable wrapper around
73 +                // a non-serializable collection, as can happen with:
74 +                // Vector.subList() => wrapped AbstractList$RandomAccessSubList
75 +                if (testImplementationDetails
76 +                    && (! c.getClass().getName().matches(
77 +                                "java.util.Collections.*")))
78 +                    throw ex;
79 +            }
80 +        }
81 +
82 +        Collection clone = cloneableClone(c);
83 +        if (clone != null)
84 +            emptyMeansEmpty(clone);
85 +    }
86 +
87 +    void emptyMeansEmpty(Collection c) throws InterruptedException {
88          assertTrue(c.isEmpty());
89          assertEquals(0, c.size());
90          assertEquals("[]", c.toString());
# Line 83 | Line 109 | public class Collection8Test extends JSR
109              assertSame(3, a[2]);
110          }
111          assertIteratorExhausted(c.iterator());
112 <        Consumer alwaysThrows = (e) -> { throw new AssertionError(); };
112 >        Consumer alwaysThrows = e -> { throw new AssertionError(); };
113          c.forEach(alwaysThrows);
114          c.iterator().forEachRemaining(alwaysThrows);
115          c.spliterator().forEachRemaining(alwaysThrows);
# Line 108 | Line 134 | public class Collection8Test extends JSR
134              assertFalse(d.removeFirstOccurrence(bomb()));
135              assertFalse(d.removeLastOccurrence(bomb()));
136          }
137 +        if (c instanceof BlockingQueue) {
138 +            BlockingQueue q = (BlockingQueue) c;
139 +            assertNull(q.poll(0L, MILLISECONDS));
140 +        }
141 +        if (c instanceof BlockingDeque) {
142 +            BlockingDeque q = (BlockingDeque) c;
143 +            assertNull(q.pollFirst(0L, MILLISECONDS));
144 +            assertNull(q.pollLast(0L, MILLISECONDS));
145 +        }
146      }
147  
148 <    public void testNullPointerExceptions() {
148 >    public void testNullPointerExceptions() throws InterruptedException {
149          Collection c = impl.emptyCollection();
150          assertThrows(
151              NullPointerException.class,
# Line 130 | Line 165 | public class Collection8Test extends JSR
165                  NullPointerException.class,
166                  () -> c.add(null));
167          }
168 <        if (!impl.permitsNulls()
134 <            && Queue.class.isAssignableFrom(impl.klazz())) {
168 >        if (!impl.permitsNulls() && c instanceof Queue) {
169              Queue q = (Queue) c;
170              assertThrows(
171                  NullPointerException.class,
172                  () -> q.offer(null));
173          }
174 <        if (!impl.permitsNulls()
141 <            && Deque.class.isAssignableFrom(impl.klazz())) {
174 >        if (!impl.permitsNulls() && c instanceof Deque) {
175              Deque d = (Deque) c;
176              assertThrows(
177                  NullPointerException.class,
# Line 149 | Line 182 | public class Collection8Test extends JSR
182                  () -> d.push(null),
183                  () -> d.descendingIterator().forEachRemaining(null));
184          }
185 +        if (c instanceof BlockingQueue) {
186 +            BlockingQueue q = (BlockingQueue) c;
187 +            assertThrows(
188 +                NullPointerException.class,
189 +                () -> {
190 +                    try { q.offer(null, 1L, HOURS); }
191 +                    catch (InterruptedException ex) {
192 +                        throw new AssertionError(ex);
193 +                    }},
194 +                () -> {
195 +                    try { q.put(null); }
196 +                    catch (InterruptedException ex) {
197 +                        throw new AssertionError(ex);
198 +                    }});
199 +        }
200 +        if (c instanceof BlockingDeque) {
201 +            BlockingDeque q = (BlockingDeque) c;
202 +            assertThrows(
203 +                NullPointerException.class,
204 +                () -> {
205 +                    try { q.offerFirst(null, 1L, HOURS); }
206 +                    catch (InterruptedException ex) {
207 +                        throw new AssertionError(ex);
208 +                    }},
209 +                () -> {
210 +                    try { q.offerLast(null, 1L, HOURS); }
211 +                    catch (InterruptedException ex) {
212 +                        throw new AssertionError(ex);
213 +                    }},
214 +                () -> {
215 +                    try { q.putFirst(null); }
216 +                    catch (InterruptedException ex) {
217 +                        throw new AssertionError(ex);
218 +                    }},
219 +                () -> {
220 +                    try { q.putLast(null); }
221 +                    catch (InterruptedException ex) {
222 +                        throw new AssertionError(ex);
223 +                    }});
224 +        }
225      }
226  
227      public void testNoSuchElementExceptions() {
# Line 157 | Line 230 | public class Collection8Test extends JSR
230              NoSuchElementException.class,
231              () -> c.iterator().next());
232  
233 <        if (Queue.class.isAssignableFrom(impl.klazz())) {
233 >        if (c instanceof Queue) {
234              Queue q = (Queue) c;
235              assertThrows(
236                  NoSuchElementException.class,
237                  () -> q.element(),
238                  () -> q.remove());
239          }
240 <        if (Deque.class.isAssignableFrom(impl.klazz())) {
240 >        if (c instanceof Deque) {
241              Deque d = (Deque) c;
242              assertThrows(
243                  NoSuchElementException.class,
# Line 179 | Line 252 | public class Collection8Test extends JSR
252  
253      public void testRemoveIf() {
254          Collection c = impl.emptyCollection();
255 +        boolean ordered =
256 +            c.spliterator().hasCharacteristics(Spliterator.ORDERED);
257          ThreadLocalRandom rnd = ThreadLocalRandom.current();
258          int n = rnd.nextInt(6);
259          for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
260          AtomicReference threwAt = new AtomicReference(null);
261 <        ArrayList survivors = new ArrayList(c);
261 >        List orig = rnd.nextBoolean()
262 >            ? new ArrayList(c)
263 >            : Arrays.asList(c.toArray());
264 >
265 >        // Merely creating an iterator can change ArrayBlockingQueue behavior
266 >        Iterator it = rnd.nextBoolean() ? c.iterator() : null;
267 >
268 >        ArrayList survivors = new ArrayList();
269          ArrayList accepts = new ArrayList();
270          ArrayList rejects = new ArrayList();
271 <        Predicate randomPredicate = (e) -> {
271 >
272 >        Predicate randomPredicate = e -> {
273              assertNull(threwAt.get());
274              switch (rnd.nextInt(3)) {
275              case 0: accepts.add(e); return true;
# Line 196 | Line 279 | public class Collection8Test extends JSR
279              }
280          };
281          try {
199            assertFalse(survivors.contains(null));
282              try {
283                  boolean modified = c.removeIf(randomPredicate);
284 <                if (!modified) {
285 <                    assertNull(threwAt.get());
286 <                    assertEquals(n, rejects.size());
287 <                    assertEquals(0, accepts.size());
284 >                assertNull(threwAt.get());
285 >                assertEquals(modified, accepts.size() > 0);
286 >                assertEquals(modified, rejects.size() != n);
287 >                assertEquals(accepts.size() + rejects.size(), n);
288 >                if (ordered) {
289 >                    assertEquals(rejects,
290 >                                 Arrays.asList(c.toArray()));
291 >                } else {
292 >                    assertEquals(new HashSet(rejects),
293 >                                 new HashSet(Arrays.asList(c.toArray())));
294                  }
295 <            } catch (ArithmeticException ok) {}
296 <            survivors.removeAll(accepts);
297 <            assertEquals(n - accepts.size(), c.size());
295 >            } catch (ArithmeticException ok) {
296 >                assertNotNull(threwAt.get());
297 >                assertTrue(c.contains(threwAt.get()));
298 >            }
299 >            if (it != null && impl.isConcurrent())
300 >                // check for weakly consistent iterator
301 >                while (it.hasNext()) assertTrue(orig.contains(it.next()));
302 >            switch (rnd.nextInt(4)) {
303 >            case 0: survivors.addAll(c); break;
304 >            case 1: survivors.addAll(Arrays.asList(c.toArray())); break;
305 >            case 2: c.forEach(e -> survivors.add(e)); break;
306 >            case 3: for (Object e : c) survivors.add(e); break;
307 >            }
308 >            assertTrue(orig.containsAll(accepts));
309 >            assertTrue(orig.containsAll(rejects));
310 >            assertTrue(orig.containsAll(survivors));
311 >            assertTrue(orig.containsAll(c));
312 >            assertTrue(c.containsAll(rejects));
313              assertTrue(c.containsAll(survivors));
314              assertTrue(survivors.containsAll(rejects));
315 <            for (Object x : accepts) assertFalse(c.contains(x));
316 <            if (threwAt.get() == null)
317 <                assertEquals(accepts.size() + rejects.size(), n);
315 >            if (threwAt.get() == null) {
316 >                assertEquals(n - accepts.size(), c.size());
317 >                for (Object x : accepts) assertFalse(c.contains(x));
318 >            } else {
319 >                // Two acceptable behaviors: entire removeIf call is one
320 >                // transaction, or each element processed is one transaction.
321 >                assertTrue(n == c.size() || n == c.size() + accepts.size());
322 >                int k = 0;
323 >                for (Object x : accepts) if (c.contains(x)) k++;
324 >                assertTrue(k == accepts.size() || k == 0);
325 >            }
326          } catch (Throwable ex) {
327              System.err.println(impl.klazz());
328 <            System.err.printf("c=%s%n", c);
328 >            // c is at risk of corruption if we got here, so be lenient
329 >            try { System.err.printf("c=%s%n", c); }
330 >            catch (Throwable t) { t.printStackTrace(); }
331              System.err.printf("n=%d%n", n);
332 +            System.err.printf("orig=%s%n", orig);
333              System.err.printf("accepts=%s%n", accepts);
334              System.err.printf("rejects=%s%n", rejects);
335              System.err.printf("survivors=%s%n", survivors);
336 <            System.err.printf("threw=%s%n", threwAt.get());
336 >            System.err.printf("threwAt=%s%n", threwAt.get());
337              throw ex;
338          }
339      }
# Line 234 | Line 348 | public class Collection8Test extends JSR
348          for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
349          ArrayList iterated = new ArrayList();
350          ArrayList iteratedForEachRemaining = new ArrayList();
351 +        ArrayList tryAdvanced = new ArrayList();
352          ArrayList spliterated = new ArrayList();
353 <        ArrayList foreached = new ArrayList();
353 >        ArrayList forEached = new ArrayList();
354 >        ArrayList removeIfed = new ArrayList();
355          for (Object x : c) iterated.add(x);
356          c.iterator().forEachRemaining(e -> iteratedForEachRemaining.add(e));
357 +        for (Spliterator s = c.spliterator();
358 +             s.tryAdvance(e -> tryAdvanced.add(e)); ) {}
359          c.spliterator().forEachRemaining(e -> spliterated.add(e));
360 <        c.forEach(e -> foreached.add(e));
360 >        c.forEach(e -> forEached.add(e));
361 >        c.removeIf(e -> { removeIfed.add(e); return false; });
362          boolean ordered =
363              c.spliterator().hasCharacteristics(Spliterator.ORDERED);
364          if (c instanceof List || c instanceof Deque)
365              assertTrue(ordered);
366          if (ordered) {
367              assertEquals(iterated, iteratedForEachRemaining);
368 +            assertEquals(iterated, tryAdvanced);
369              assertEquals(iterated, spliterated);
370 <            assertEquals(iterated, foreached);
370 >            assertEquals(iterated, forEached);
371 >            assertEquals(iterated, removeIfed);
372          } else {
373              HashSet cset = new HashSet(c);
374              assertEquals(cset, new HashSet(iterated));
375              assertEquals(cset, new HashSet(iteratedForEachRemaining));
376 +            assertEquals(cset, new HashSet(tryAdvanced));
377              assertEquals(cset, new HashSet(spliterated));
378 <            assertEquals(cset, new HashSet(foreached));
378 >            assertEquals(cset, new HashSet(forEached));
379 >            assertEquals(cset, new HashSet(removeIfed));
380          }
381          if (c instanceof Deque) {
382              Deque d = (Deque) c;
# Line 272 | Line 395 | public class Collection8Test extends JSR
395  
396      /**
397       * Calling Iterator#remove() after Iterator#forEachRemaining
398 <     * should remove last element
398 >     * should (maybe) remove last element
399       */
400      public void testRemoveAfterForEachRemaining() {
401          Collection c = impl.emptyCollection();
402          ThreadLocalRandom rnd = ThreadLocalRandom.current();
403 <        {
403 >        testCollection: {
404              int n = 3 + rnd.nextInt(2);
405              for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
406              Iterator it = c.iterator();
# Line 285 | Line 408 | public class Collection8Test extends JSR
408              assertEquals(impl.makeElement(0), it.next());
409              assertTrue(it.hasNext());
410              assertEquals(impl.makeElement(1), it.next());
411 <            it.forEachRemaining((e) -> {});
412 <            it.remove();
413 <            assertEquals(n - 1, c.size());
414 <            for (int i = 0; i < n - 1; i++)
415 <                assertTrue(c.contains(impl.makeElement(i)));
416 <            assertFalse(c.contains(impl.makeElement(n - 1)));
411 >            it.forEachRemaining(e -> assertTrue(c.contains(e)));
412 >            if (testImplementationDetails) {
413 >                if (c instanceof java.util.concurrent.ArrayBlockingQueue) {
414 >                    assertIteratorExhausted(it);
415 >                } else {
416 >                    try { it.remove(); }
417 >                    catch (UnsupportedOperationException ok) {
418 >                        break testCollection;
419 >                    }
420 >                    assertEquals(n - 1, c.size());
421 >                    for (int i = 0; i < n - 1; i++)
422 >                        assertTrue(c.contains(impl.makeElement(i)));
423 >                    assertFalse(c.contains(impl.makeElement(n - 1)));
424 >                }
425 >            }
426          }
427          if (c instanceof Deque) {
428              Deque d = (Deque) impl.emptyCollection();
# Line 301 | Line 433 | public class Collection8Test extends JSR
433              assertEquals(impl.makeElement(n - 1), it.next());
434              assertTrue(it.hasNext());
435              assertEquals(impl.makeElement(n - 2), it.next());
436 <            it.forEachRemaining((e) -> {});
437 <            it.remove();
438 <            assertEquals(n - 1, d.size());
439 <            for (int i = 1; i < n; i++)
440 <                assertTrue(d.contains(impl.makeElement(i)));
441 <            assertFalse(d.contains(impl.makeElement(0)));
436 >            it.forEachRemaining(e -> assertTrue(c.contains(e)));
437 >            if (testImplementationDetails) {
438 >                it.remove();
439 >                assertEquals(n - 1, d.size());
440 >                for (int i = 1; i < n; i++)
441 >                    assertTrue(d.contains(impl.makeElement(i)));
442 >                assertFalse(d.contains(impl.makeElement(0)));
443 >            }
444          }
445      }
446  
# Line 319 | Line 453 | public class Collection8Test extends JSR
453          final Object x = impl.makeElement(1);
454          final Object y = impl.makeElement(2);
455          final ArrayList found = new ArrayList();
456 <        Consumer<Object> spy = (o) -> { found.add(o); };
456 >        Consumer<Object> spy = o -> found.add(o);
457          c.stream().forEach(spy);
458          assertTrue(found.isEmpty());
459  
# Line 353 | Line 487 | public class Collection8Test extends JSR
487              Runnable checkElt = () -> {
488                  threadsStarted.countDown();
489                  while (!done.get())
490 <                    c.stream().forEach((x) -> { assertSame(x, elt); }); };
490 >                    c.stream().forEach(x -> assertSame(x, elt)); };
491              Runnable addRemove = () -> {
492                  threadsStarted.countDown();
493                  while (!done.get()) {
# Line 377 | Line 511 | public class Collection8Test extends JSR
511          final Object x = impl.makeElement(1);
512          final Object y = impl.makeElement(2);
513          final ArrayList found = new ArrayList();
514 <        Consumer<Object> spy = (o) -> { found.add(o); };
514 >        Consumer<Object> spy = o -> found.add(o);
515          c.forEach(spy);
516          assertTrue(found.isEmpty());
517  
# Line 411 | Line 545 | public class Collection8Test extends JSR
545              Runnable checkElt = () -> {
546                  threadsStarted.countDown();
547                  while (!done.get())
548 <                    c.forEach((x) -> { assertSame(x, elt); }); };
548 >                    c.forEach(x -> assertSame(x, elt)); };
549              Runnable addRemove = () -> {
550                  threadsStarted.countDown();
551                  while (!done.get()) {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines