2

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.

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunatelly problem still exists. Please see edited post.
@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.
0

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

with(arrDeltaBrainWaves.iterator()) {
 forEach {
    
 }
}

5 Comments

Unfortunatelly problem still exists. Please see edited post.
I tried the code but I don't see any exception. Are you sure the exception is caused due in this code snippet. Can you add more of your code please?
not fixing the error
@AsthaGarg Can you show your code? May be create a new question and share the link.
noting different in my code same as this question, your answer does not solve the problem
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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.