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