1

I have problem with ConcurrentModificationException. Here's my part of the code :

    var deltaSum = 0
    arrDeltaBrainWaves.map {
         value -> deltaSum += value
   }

To be clear - I know why this error appears :) The problem is - I have no idea what's the solution ? Do I really need to create new temp list and put values there ? It just doesnt make sense :) Any better options, please ?

EDIT:

I changed the code to below :

var deltaSum = 0
                                with(arrDeltaBrainWaves.iterator()) {
                                    forEach {
                                        deltaSum += it
                                    }
                                }
                                avgDelta = deltaSum / arrDeltaBrainWaves.size

But problem still exists.

Bartos
  • 1,007
  • 3
  • 15
  • 38

3 Answers3

2

you need to use the Iterators

example:

val myCollection = mutableListOf(1,2,3,4)
val iterator = myCollection.iterator()
while(iterator.hasNext()){
    val item = iterator.next()
    //do something
}

this will avoid ConcurrentModificationExceptions

Reza Abedi
  • 419
  • 4
  • 16
  • 1
    Unfortunatelly problem still exists. Please see edited post. – Bartos Oct 02 '21 at 09:53
  • 1
    @Bartos The main reason of happening this exception is you may have some code that modifies on this array. Just test two item and let me update about it. first, add `Volatile` to your array and run your code inside of `Synchronized` Blocks. seccond, could you change array to hashmap? if yes this should solve this exception. – Reza Abedi Oct 03 '21 at 00:30
0

The ConcurrentModificationException can be avoided by using iterators. Here is kotlin way to do so:

with(arrDeltaBrainWaves.iterator()) {
 forEach {
    
 }
}
akhil nair
  • 1,371
  • 1
  • 11
  • 19
0

I solved the ConcurrentModificationException by using MutableListIterator in Kotlin

OLD CODE :

registeredListeners.forEach { it.notifyObservers() }

(In my case notifyObservers() is removing object from the registeredListeners list which is the cause of the exception)

NEW CODE :

val iterator = registeredListeners.toMutableList().listIterator()
while (iterator.hasNext()) {
    iterator.next().notifyObservers()
}

Hope it helps :)

Astha Garg
  • 1,022
  • 7
  • 21