1
+ package com.baeldung.concurrentmodificationexception
2
+
3
+ import org.junit.jupiter.api.Assertions.assertEquals
4
+ import org.junit.jupiter.api.Test
5
+ import org.junit.jupiter.api.assertThrows
6
+ import java.util.*
7
+ import java.util.concurrent.CopyOnWriteArrayList
8
+
9
+ class ConcurrentModificationExceptionUnitTest {
10
+
11
+
12
+ @Test
13
+ fun `given list when remove during iteration then throw ConcurrentModificationException` () {
14
+ val numbers = mutableListOf (1 , 2 , 3 , 4 , 5 )
15
+
16
+ assertThrows<ConcurrentModificationException > {
17
+ for (item in numbers) {
18
+ if (item == 3 ) {
19
+ numbers.remove(item)
20
+ }
21
+ }
22
+ }
23
+ }
24
+
25
+ @Test
26
+ fun `given list when remove with iterator then list is updated` () {
27
+ val numbers = mutableListOf (1 , 2 , 3 , 4 , 5 )
28
+ val iterator = numbers.iterator()
29
+ while (iterator.hasNext()) {
30
+ val number = iterator.next()
31
+ if (number == 3 ) {
32
+ iterator.remove()
33
+ }
34
+ }
35
+
36
+ assertEquals(listOf (1 , 2 , 4 , 5 ), numbers)
37
+ }
38
+
39
+ @Test
40
+ fun `given list when removeAll by condition then list is updated` () {
41
+ val numbers = mutableListOf (1 , 2 , 3 , 4 , 5 )
42
+ numbers.removeAll { number -> number == 3 }
43
+
44
+ assertEquals(listOf (1 , 2 , 4 , 5 ), numbers)
45
+ }
46
+
47
+ @Test
48
+ fun `given list and copy when modify copy then update list` () {
49
+ var numbers = mutableListOf (1 , 2 , 3 , 4 , 5 )
50
+ val copyNumbers = numbers.toMutableList()
51
+
52
+ for (number in numbers) {
53
+ if (number == 3 ) {
54
+ copyNumbers.remove(number)
55
+ }
56
+ }
57
+
58
+ numbers = copyNumbers
59
+
60
+ assertEquals(listOf (1 , 2 , 4 , 5 ), numbers)
61
+ }
62
+
63
+ @Test
64
+ fun `given CopyOnWriteArrayList when remove items then items removed` () {
65
+ val list = CopyOnWriteArrayList (listOf (1 , 2 , 3 , 4 , 5 ))
66
+
67
+ for (item in list) {
68
+ if (item == 3 ) {
69
+ list.remove(item)
70
+ }
71
+ }
72
+
73
+ assertEquals(listOf (1 , 2 , 4 , 5 ), list)
74
+ }
75
+
76
+ }
0 commit comments