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