1 |
/* |
2 |
* Written by Doug Lea and Martin Buchholz with assistance from |
3 |
* members of JCP JSR-166 Expert Group and released to the public |
4 |
* domain, as explained at |
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 |
|
37 |
/** |
38 |
* Contains tests applicable to all jdk8+ Collection implementations. |
39 |
* An extension of CollectionTest. |
40 |
*/ |
41 |
public class Collection8Test extends JSR166TestCase { |
42 |
final CollectionImplementation impl; |
43 |
|
44 |
/** Tests are parameterized by a Collection implementation. */ |
45 |
Collection8Test(CollectionImplementation impl, String methodName) { |
46 |
super(methodName); |
47 |
this.impl = impl; |
48 |
} |
49 |
|
50 |
public static Test testSuite(CollectionImplementation impl) { |
51 |
return parameterizedTestSuite(Collection8Test.class, |
52 |
CollectionImplementation.class, |
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 |
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
245 |
int n = rnd.nextInt(6); |
246 |
for (int i = 0; i < n; i++) c.add(impl.makeElement(i)); |
247 |
AtomicReference threwAt = new AtomicReference(null); |
248 |
List orig = rnd.nextBoolean() |
249 |
? new ArrayList(c) |
250 |
: Arrays.asList(c.toArray()); |
251 |
|
252 |
// Merely creating an iterator can change ArrayBlockingQueue behavior |
253 |
Iterator it = rnd.nextBoolean() ? c.iterator() : null; |
254 |
|
255 |
ArrayList survivors = new ArrayList(); |
256 |
ArrayList accepts = new ArrayList(); |
257 |
ArrayList rejects = new ArrayList(); |
258 |
|
259 |
Predicate randomPredicate = e -> { |
260 |
assertNull(threwAt.get()); |
261 |
switch (rnd.nextInt(3)) { |
262 |
case 0: accepts.add(e); return true; |
263 |
case 1: rejects.add(e); return false; |
264 |
case 2: threwAt.set(e); throw new ArithmeticException(); |
265 |
default: throw new AssertionError(); |
266 |
} |
267 |
}; |
268 |
try { |
269 |
try { |
270 |
boolean modified = c.removeIf(randomPredicate); |
271 |
assertNull(threwAt.get()); |
272 |
assertEquals(modified, accepts.size() > 0); |
273 |
assertEquals(modified, rejects.size() != n); |
274 |
assertEquals(accepts.size() + rejects.size(), n); |
275 |
assertEquals(rejects, Arrays.asList(c.toArray())); |
276 |
} catch (ArithmeticException ok) { |
277 |
assertNotNull(threwAt.get()); |
278 |
assertTrue(c.contains(threwAt.get())); |
279 |
} |
280 |
if (it != null && impl.isConcurrent()) |
281 |
// check for weakly consistent iterator |
282 |
while (it.hasNext()) assertTrue(orig.contains(it.next())); |
283 |
switch (rnd.nextInt(4)) { |
284 |
case 0: survivors.addAll(c); break; |
285 |
case 1: survivors.addAll(Arrays.asList(c.toArray())); break; |
286 |
case 2: c.forEach(e -> survivors.add(e)); break; |
287 |
case 3: for (Object e : c) survivors.add(e); break; |
288 |
} |
289 |
assertTrue(orig.containsAll(accepts)); |
290 |
assertTrue(orig.containsAll(rejects)); |
291 |
assertTrue(orig.containsAll(survivors)); |
292 |
assertTrue(orig.containsAll(c)); |
293 |
assertTrue(c.containsAll(rejects)); |
294 |
assertTrue(c.containsAll(survivors)); |
295 |
assertTrue(survivors.containsAll(rejects)); |
296 |
assertEquals(n - accepts.size(), c.size()); |
297 |
for (Object x : accepts) assertFalse(c.contains(x)); |
298 |
} catch (Throwable ex) { |
299 |
System.err.println(impl.klazz()); |
300 |
System.err.printf("c=%s%n", c); |
301 |
System.err.printf("n=%d%n", n); |
302 |
System.err.printf("orig=%s%n", orig); |
303 |
System.err.printf("accepts=%s%n", accepts); |
304 |
System.err.printf("rejects=%s%n", rejects); |
305 |
System.err.printf("survivors=%s%n", survivors); |
306 |
System.err.printf("threwAt=%s%n", threwAt.get()); |
307 |
throw ex; |
308 |
} |
309 |
} |
310 |
|
311 |
/** |
312 |
* Various ways of traversing a collection yield same elements |
313 |
*/ |
314 |
public void testIteratorEquivalence() { |
315 |
Collection c = impl.emptyCollection(); |
316 |
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
317 |
int n = rnd.nextInt(6); |
318 |
for (int i = 0; i < n; i++) c.add(impl.makeElement(i)); |
319 |
ArrayList iterated = new ArrayList(); |
320 |
ArrayList iteratedForEachRemaining = new ArrayList(); |
321 |
ArrayList tryAdvanced = new ArrayList(); |
322 |
ArrayList spliterated = new ArrayList(); |
323 |
ArrayList forEached = new ArrayList(); |
324 |
ArrayList removeIfed = new ArrayList(); |
325 |
for (Object x : c) iterated.add(x); |
326 |
c.iterator().forEachRemaining(e -> iteratedForEachRemaining.add(e)); |
327 |
for (Spliterator s = c.spliterator(); |
328 |
s.tryAdvance(e -> tryAdvanced.add(e)); ) {} |
329 |
c.spliterator().forEachRemaining(e -> spliterated.add(e)); |
330 |
c.forEach(e -> forEached.add(e)); |
331 |
c.removeIf(e -> { removeIfed.add(e); return false; }); |
332 |
boolean ordered = |
333 |
c.spliterator().hasCharacteristics(Spliterator.ORDERED); |
334 |
if (c instanceof List || c instanceof Deque) |
335 |
assertTrue(ordered); |
336 |
if (ordered) { |
337 |
assertEquals(iterated, iteratedForEachRemaining); |
338 |
assertEquals(iterated, tryAdvanced); |
339 |
assertEquals(iterated, spliterated); |
340 |
assertEquals(iterated, forEached); |
341 |
assertEquals(iterated, removeIfed); |
342 |
} else { |
343 |
HashSet cset = new HashSet(c); |
344 |
assertEquals(cset, new HashSet(iterated)); |
345 |
assertEquals(cset, new HashSet(iteratedForEachRemaining)); |
346 |
assertEquals(cset, new HashSet(tryAdvanced)); |
347 |
assertEquals(cset, new HashSet(spliterated)); |
348 |
assertEquals(cset, new HashSet(forEached)); |
349 |
assertEquals(cset, new HashSet(removeIfed)); |
350 |
} |
351 |
if (c instanceof Deque) { |
352 |
Deque d = (Deque) c; |
353 |
ArrayList descending = new ArrayList(); |
354 |
ArrayList descendingForEachRemaining = new ArrayList(); |
355 |
for (Iterator it = d.descendingIterator(); it.hasNext(); ) |
356 |
descending.add(it.next()); |
357 |
d.descendingIterator().forEachRemaining( |
358 |
e -> descendingForEachRemaining.add(e)); |
359 |
Collections.reverse(descending); |
360 |
Collections.reverse(descendingForEachRemaining); |
361 |
assertEquals(iterated, descending); |
362 |
assertEquals(iterated, descendingForEachRemaining); |
363 |
} |
364 |
} |
365 |
|
366 |
/** |
367 |
* Calling Iterator#remove() after Iterator#forEachRemaining |
368 |
* should (maybe) remove last element |
369 |
*/ |
370 |
public void testRemoveAfterForEachRemaining() { |
371 |
Collection c = impl.emptyCollection(); |
372 |
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
373 |
{ |
374 |
int n = 3 + rnd.nextInt(2); |
375 |
for (int i = 0; i < n; i++) c.add(impl.makeElement(i)); |
376 |
Iterator it = c.iterator(); |
377 |
assertTrue(it.hasNext()); |
378 |
assertEquals(impl.makeElement(0), it.next()); |
379 |
assertTrue(it.hasNext()); |
380 |
assertEquals(impl.makeElement(1), it.next()); |
381 |
it.forEachRemaining(e -> assertTrue(c.contains(e))); |
382 |
if (testImplementationDetails) { |
383 |
if (c instanceof java.util.concurrent.ArrayBlockingQueue) { |
384 |
assertIteratorExhausted(it); |
385 |
} else { |
386 |
it.remove(); |
387 |
assertEquals(n - 1, c.size()); |
388 |
for (int i = 0; i < n - 1; i++) |
389 |
assertTrue(c.contains(impl.makeElement(i))); |
390 |
assertFalse(c.contains(impl.makeElement(n - 1))); |
391 |
} |
392 |
} |
393 |
} |
394 |
if (c instanceof Deque) { |
395 |
Deque d = (Deque) impl.emptyCollection(); |
396 |
int n = 3 + rnd.nextInt(2); |
397 |
for (int i = 0; i < n; i++) d.add(impl.makeElement(i)); |
398 |
Iterator it = d.descendingIterator(); |
399 |
assertTrue(it.hasNext()); |
400 |
assertEquals(impl.makeElement(n - 1), it.next()); |
401 |
assertTrue(it.hasNext()); |
402 |
assertEquals(impl.makeElement(n - 2), it.next()); |
403 |
it.forEachRemaining(e -> assertTrue(c.contains(e))); |
404 |
if (testImplementationDetails) { |
405 |
it.remove(); |
406 |
assertEquals(n - 1, d.size()); |
407 |
for (int i = 1; i < n; i++) |
408 |
assertTrue(d.contains(impl.makeElement(i))); |
409 |
assertFalse(d.contains(impl.makeElement(0))); |
410 |
} |
411 |
} |
412 |
} |
413 |
|
414 |
/** |
415 |
* stream().forEach returns elements in the collection |
416 |
*/ |
417 |
public void testStreamForEach() throws Throwable { |
418 |
final Collection c = impl.emptyCollection(); |
419 |
final AtomicLong count = new AtomicLong(0L); |
420 |
final Object x = impl.makeElement(1); |
421 |
final Object y = impl.makeElement(2); |
422 |
final ArrayList found = new ArrayList(); |
423 |
Consumer<Object> spy = o -> found.add(o); |
424 |
c.stream().forEach(spy); |
425 |
assertTrue(found.isEmpty()); |
426 |
|
427 |
assertTrue(c.add(x)); |
428 |
c.stream().forEach(spy); |
429 |
assertEquals(Collections.singletonList(x), found); |
430 |
found.clear(); |
431 |
|
432 |
assertTrue(c.add(y)); |
433 |
c.stream().forEach(spy); |
434 |
assertEquals(2, found.size()); |
435 |
assertTrue(found.contains(x)); |
436 |
assertTrue(found.contains(y)); |
437 |
found.clear(); |
438 |
|
439 |
c.clear(); |
440 |
c.stream().forEach(spy); |
441 |
assertTrue(found.isEmpty()); |
442 |
} |
443 |
|
444 |
public void testStreamForEachConcurrentStressTest() throws Throwable { |
445 |
if (!impl.isConcurrent()) return; |
446 |
final Collection c = impl.emptyCollection(); |
447 |
final long testDurationMillis = timeoutMillis(); |
448 |
final AtomicBoolean done = new AtomicBoolean(false); |
449 |
final Object elt = impl.makeElement(1); |
450 |
final Future<?> f1, f2; |
451 |
final ExecutorService pool = Executors.newCachedThreadPool(); |
452 |
try (PoolCleaner cleaner = cleaner(pool, done)) { |
453 |
final CountDownLatch threadsStarted = new CountDownLatch(2); |
454 |
Runnable checkElt = () -> { |
455 |
threadsStarted.countDown(); |
456 |
while (!done.get()) |
457 |
c.stream().forEach(x -> assertSame(x, elt)); }; |
458 |
Runnable addRemove = () -> { |
459 |
threadsStarted.countDown(); |
460 |
while (!done.get()) { |
461 |
assertTrue(c.add(elt)); |
462 |
assertTrue(c.remove(elt)); |
463 |
}}; |
464 |
f1 = pool.submit(checkElt); |
465 |
f2 = pool.submit(addRemove); |
466 |
Thread.sleep(testDurationMillis); |
467 |
} |
468 |
assertNull(f1.get(0L, MILLISECONDS)); |
469 |
assertNull(f2.get(0L, MILLISECONDS)); |
470 |
} |
471 |
|
472 |
/** |
473 |
* collection.forEach returns elements in the collection |
474 |
*/ |
475 |
public void testForEach() throws Throwable { |
476 |
final Collection c = impl.emptyCollection(); |
477 |
final AtomicLong count = new AtomicLong(0L); |
478 |
final Object x = impl.makeElement(1); |
479 |
final Object y = impl.makeElement(2); |
480 |
final ArrayList found = new ArrayList(); |
481 |
Consumer<Object> spy = o -> found.add(o); |
482 |
c.forEach(spy); |
483 |
assertTrue(found.isEmpty()); |
484 |
|
485 |
assertTrue(c.add(x)); |
486 |
c.forEach(spy); |
487 |
assertEquals(Collections.singletonList(x), found); |
488 |
found.clear(); |
489 |
|
490 |
assertTrue(c.add(y)); |
491 |
c.forEach(spy); |
492 |
assertEquals(2, found.size()); |
493 |
assertTrue(found.contains(x)); |
494 |
assertTrue(found.contains(y)); |
495 |
found.clear(); |
496 |
|
497 |
c.clear(); |
498 |
c.forEach(spy); |
499 |
assertTrue(found.isEmpty()); |
500 |
} |
501 |
|
502 |
public void testForEachConcurrentStressTest() throws Throwable { |
503 |
if (!impl.isConcurrent()) return; |
504 |
final Collection c = impl.emptyCollection(); |
505 |
final long testDurationMillis = timeoutMillis(); |
506 |
final AtomicBoolean done = new AtomicBoolean(false); |
507 |
final Object elt = impl.makeElement(1); |
508 |
final Future<?> f1, f2; |
509 |
final ExecutorService pool = Executors.newCachedThreadPool(); |
510 |
try (PoolCleaner cleaner = cleaner(pool, done)) { |
511 |
final CountDownLatch threadsStarted = new CountDownLatch(2); |
512 |
Runnable checkElt = () -> { |
513 |
threadsStarted.countDown(); |
514 |
while (!done.get()) |
515 |
c.forEach(x -> assertSame(x, elt)); }; |
516 |
Runnable addRemove = () -> { |
517 |
threadsStarted.countDown(); |
518 |
while (!done.get()) { |
519 |
assertTrue(c.add(elt)); |
520 |
assertTrue(c.remove(elt)); |
521 |
}}; |
522 |
f1 = pool.submit(checkElt); |
523 |
f2 = pool.submit(addRemove); |
524 |
Thread.sleep(testDurationMillis); |
525 |
} |
526 |
assertNull(f1.get(0L, MILLISECONDS)); |
527 |
assertNull(f2.get(0L, MILLISECONDS)); |
528 |
} |
529 |
|
530 |
// public void testCollection8DebugFail() { |
531 |
// fail(impl.klazz().getSimpleName()); |
532 |
// } |
533 |
} |