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.22 by jsr166, Sun Nov 13 02:10:10 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 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());
# Line 83 | Line 98 | public class Collection8Test extends JSR
98              assertSame(3, a[2]);
99          }
100          assertIteratorExhausted(c.iterator());
101 <        Consumer alwaysThrows = (e) -> { throw new AssertionError(); };
101 >        Consumer alwaysThrows = e -> { throw new AssertionError(); };
102          c.forEach(alwaysThrows);
103          c.iterator().forEachRemaining(alwaysThrows);
104          c.spliterator().forEachRemaining(alwaysThrows);
# Line 108 | Line 123 | public class Collection8Test extends JSR
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() {
137 >    public void testNullPointerExceptions() throws InterruptedException {
138          Collection c = impl.emptyCollection();
139          assertThrows(
140              NullPointerException.class,
# Line 130 | Line 154 | public class Collection8Test extends JSR
154                  NullPointerException.class,
155                  () -> c.add(null));
156          }
157 <        if (!impl.permitsNulls()
134 <            && Queue.class.isAssignableFrom(impl.klazz())) {
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()
141 <            && Deque.class.isAssignableFrom(impl.klazz())) {
163 >        if (!impl.permitsNulls() && c instanceof Deque) {
164              Deque d = (Deque) c;
165              assertThrows(
166                  NullPointerException.class,
# Line 149 | Line 171 | public class Collection8Test extends JSR
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() {
# Line 157 | Line 219 | public class Collection8Test extends JSR
219              NoSuchElementException.class,
220              () -> c.iterator().next());
221  
222 <        if (Queue.class.isAssignableFrom(impl.klazz())) {
222 >        if (c instanceof Queue) {
223              Queue q = (Queue) c;
224              assertThrows(
225                  NoSuchElementException.class,
226                  () -> q.element(),
227                  () -> q.remove());
228          }
229 <        if (Deque.class.isAssignableFrom(impl.klazz())) {
229 >        if (c instanceof Deque) {
230              Deque d = (Deque) c;
231              assertThrows(
232                  NoSuchElementException.class,
# Line 179 | Line 241 | public class Collection8Test extends JSR
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 <        ArrayList survivors = new ArrayList(c);
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 <        Predicate randomPredicate = (e) -> {
260 >
261 >        Predicate randomPredicate = e -> {
262              assertNull(threwAt.get());
263              switch (rnd.nextInt(3)) {
264              case 0: accepts.add(e); return true;
# Line 196 | Line 268 | public class Collection8Test extends JSR
268              }
269          };
270          try {
199            assertFalse(survivors.contains(null));
271              try {
272                  boolean modified = c.removeIf(randomPredicate);
273 <                if (!modified) {
274 <                    assertNull(threwAt.get());
275 <                    assertEquals(n, rejects.size());
276 <                    assertEquals(0, accepts.size());
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 <            survivors.removeAll(accepts);
286 <            assertEquals(n - accepts.size(), c.size());
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 <            for (Object x : accepts) assertFalse(c.contains(x));
305 <            if (threwAt.get() == null)
306 <                assertEquals(accepts.size() + rejects.size(), n);
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              System.err.printf("c=%s%n", c);
318              System.err.printf("n=%d%n", n);
319 +            System.err.printf("orig=%s%n", orig);
320              System.err.printf("accepts=%s%n", accepts);
321              System.err.printf("rejects=%s%n", rejects);
322              System.err.printf("survivors=%s%n", survivors);
323 <            System.err.printf("threw=%s%n", threwAt.get());
323 >            System.err.printf("threwAt=%s%n", threwAt.get());
324              throw ex;
325          }
326      }
# Line 234 | Line 335 | public class Collection8Test extends JSR
335          for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
336          ArrayList iterated = new ArrayList();
337          ArrayList iteratedForEachRemaining = new ArrayList();
338 +        ArrayList tryAdvanced = new ArrayList();
339          ArrayList spliterated = new ArrayList();
340 <        ArrayList foreached = new ArrayList();
340 >        ArrayList forEached = new ArrayList();
341 >        ArrayList removeIfed = new ArrayList();
342          for (Object x : c) iterated.add(x);
343          c.iterator().forEachRemaining(e -> iteratedForEachRemaining.add(e));
344 +        for (Spliterator s = c.spliterator();
345 +             s.tryAdvance(e -> tryAdvanced.add(e)); ) {}
346          c.spliterator().forEachRemaining(e -> spliterated.add(e));
347 <        c.forEach(e -> foreached.add(e));
347 >        c.forEach(e -> forEached.add(e));
348 >        c.removeIf(e -> { removeIfed.add(e); return false; });
349          boolean ordered =
350              c.spliterator().hasCharacteristics(Spliterator.ORDERED);
351          if (c instanceof List || c instanceof Deque)
352              assertTrue(ordered);
353          if (ordered) {
354              assertEquals(iterated, iteratedForEachRemaining);
355 +            assertEquals(iterated, tryAdvanced);
356              assertEquals(iterated, spliterated);
357 <            assertEquals(iterated, foreached);
357 >            assertEquals(iterated, forEached);
358 >            assertEquals(iterated, removeIfed);
359          } else {
360              HashSet cset = new HashSet(c);
361              assertEquals(cset, new HashSet(iterated));
362              assertEquals(cset, new HashSet(iteratedForEachRemaining));
363 +            assertEquals(cset, new HashSet(tryAdvanced));
364              assertEquals(cset, new HashSet(spliterated));
365 <            assertEquals(cset, new HashSet(foreached));
365 >            assertEquals(cset, new HashSet(forEached));
366 >            assertEquals(cset, new HashSet(removeIfed));
367          }
368          if (c instanceof Deque) {
369              Deque d = (Deque) c;
# Line 272 | Line 382 | public class Collection8Test extends JSR
382  
383      /**
384       * Calling Iterator#remove() after Iterator#forEachRemaining
385 <     * should remove last element
385 >     * should (maybe) remove last element
386       */
387      public void testRemoveAfterForEachRemaining() {
388          Collection c = impl.emptyCollection();
# Line 285 | Line 395 | public class Collection8Test extends JSR
395              assertEquals(impl.makeElement(0), it.next());
396              assertTrue(it.hasNext());
397              assertEquals(impl.makeElement(1), it.next());
398 <            it.forEachRemaining((e) -> {});
399 <            it.remove();
400 <            assertEquals(n - 1, c.size());
401 <            for (int i = 0; i < n - 1; i++)
402 <                assertTrue(c.contains(impl.makeElement(i)));
403 <            assertFalse(c.contains(impl.makeElement(n - 1)));
398 >            it.forEachRemaining(e -> assertTrue(c.contains(e)));
399 >            if (testImplementationDetails) {
400 >                if (c instanceof java.util.concurrent.ArrayBlockingQueue) {
401 >                    assertIteratorExhausted(it);
402 >                } else {
403 >                    it.remove();
404 >                    assertEquals(n - 1, c.size());
405 >                    for (int i = 0; i < n - 1; i++)
406 >                        assertTrue(c.contains(impl.makeElement(i)));
407 >                    assertFalse(c.contains(impl.makeElement(n - 1)));
408 >                }
409 >            }
410          }
411          if (c instanceof Deque) {
412              Deque d = (Deque) impl.emptyCollection();
# Line 301 | Line 417 | public class Collection8Test extends JSR
417              assertEquals(impl.makeElement(n - 1), it.next());
418              assertTrue(it.hasNext());
419              assertEquals(impl.makeElement(n - 2), it.next());
420 <            it.forEachRemaining((e) -> {});
421 <            it.remove();
422 <            assertEquals(n - 1, d.size());
423 <            for (int i = 1; i < n; i++)
424 <                assertTrue(d.contains(impl.makeElement(i)));
425 <            assertFalse(d.contains(impl.makeElement(0)));
420 >            it.forEachRemaining(e -> assertTrue(c.contains(e)));
421 >            if (testImplementationDetails) {
422 >                it.remove();
423 >                assertEquals(n - 1, d.size());
424 >                for (int i = 1; i < n; i++)
425 >                    assertTrue(d.contains(impl.makeElement(i)));
426 >                assertFalse(d.contains(impl.makeElement(0)));
427 >            }
428          }
429      }
430  
# Line 319 | Line 437 | public class Collection8Test extends JSR
437          final Object x = impl.makeElement(1);
438          final Object y = impl.makeElement(2);
439          final ArrayList found = new ArrayList();
440 <        Consumer<Object> spy = (o) -> { found.add(o); };
440 >        Consumer<Object> spy = o -> found.add(o);
441          c.stream().forEach(spy);
442          assertTrue(found.isEmpty());
443  
# Line 353 | Line 471 | public class Collection8Test extends JSR
471              Runnable checkElt = () -> {
472                  threadsStarted.countDown();
473                  while (!done.get())
474 <                    c.stream().forEach((x) -> { assertSame(x, elt); }); };
474 >                    c.stream().forEach(x -> assertSame(x, elt)); };
475              Runnable addRemove = () -> {
476                  threadsStarted.countDown();
477                  while (!done.get()) {
# Line 377 | Line 495 | public class Collection8Test extends JSR
495          final Object x = impl.makeElement(1);
496          final Object y = impl.makeElement(2);
497          final ArrayList found = new ArrayList();
498 <        Consumer<Object> spy = (o) -> { found.add(o); };
498 >        Consumer<Object> spy = o -> found.add(o);
499          c.forEach(spy);
500          assertTrue(found.isEmpty());
501  
# Line 411 | Line 529 | public class Collection8Test extends JSR
529              Runnable checkElt = () -> {
530                  threadsStarted.countDown();
531                  while (!done.get())
532 <                    c.forEach((x) -> { assertSame(x, elt); }); };
532 >                    c.forEach(x -> assertSame(x, elt)); };
533              Runnable addRemove = () -> {
534                  threadsStarted.countDown();
535                  while (!done.get()) {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines