Skip to content

Commit c40d696

Browse files
committed
Added ConcurrentModificationException test
1 parent c198a96 commit c40d696

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.baeldung.java.concurrentmodificationexception;
2+
3+
import org.assertj.core.api.Assertions;
4+
import org.junit.Test;
5+
6+
import java.util.ArrayList;
7+
import java.util.ConcurrentModificationException;
8+
import java.util.Iterator;
9+
10+
import static org.assertj.core.api.Assertions.assertThat;
11+
import static org.assertj.core.util.Lists.newArrayList;
12+
13+
public class ConcurrentModificationUnitTest {
14+
@Test(expected = ConcurrentModificationException.class)
15+
public void whilstRemovingDuringIteration_shouldThrowException() throws InterruptedException {
16+
17+
ArrayList<Integer> integers = newArrayList(1, 2, 3);
18+
19+
for (Integer integer : integers) {
20+
integers.remove(1);
21+
}
22+
}
23+
24+
@Test
25+
public void whilstRemovingDuringIteration_shouldNotThrowException() throws InterruptedException {
26+
27+
ArrayList<Integer> integers = newArrayList(1, 2, 3);
28+
29+
for (Iterator<Integer> iterator = integers.iterator(); iterator.hasNext();) {
30+
Integer integer = iterator.next();
31+
if(integer == 2) {
32+
iterator.remove();
33+
}
34+
}
35+
36+
assertThat(integers).containsExactly(1, 3);
37+
}
38+
39+
@Test
40+
public void whilstRemovingDuringForEach_shouldNotThrowException() throws InterruptedException {
41+
42+
ArrayList<Integer> integers = newArrayList(1, 2, 3);
43+
ArrayList<Integer> toRemove = newArrayList();
44+
45+
for (Integer integer : integers) {
46+
if(integer == 2) {
47+
toRemove.add(integer);
48+
}
49+
}
50+
integers.removeAll(toRemove);
51+
52+
assertThat(integers).containsExactly(1, 3);
53+
}
54+
}

0 commit comments

Comments
 (0)