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