-1

I'm getting concurrent exception replacing string inside iterator.

fun replaceValuesInURLString(allFieldsValues: HashMap<String, UserSelectedData>, urlString: String): String {
        var result = urlString
        val iteratorValues = allFieldsValues.iterator()
        while(iteratorValues.hasNext()){
            val fieldValue = iteratorValues.next()
            val key = "$${fieldValue.key}$"
            result = result.replace(key, fieldValue.value.getDataForReg()?: "")
        }
        //Regex replace to remove query param value's which are not replaced by earlier code
        val cleanUpRegex = "(\\\$)(.*?)(\\\$)".toRegex()
        return cleanUpRegex.replace(result,"")
    }

I'm getting concurrent exception on following line of above method.

result = result.replace(key, fieldValue.value.getDataForReg()?: "")

stacktrace is

    java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextNode(HashMap.java:1441)
        at java.util.HashMap$EntryIterator.next(HashMap.java:1475)
        at java.util.HashMap$EntryIterator.next(HashMap.java:1475)
        at Validator$DefaultImpls.replaceValuesInURLString(Validator.kt:32)
        at replaceValuesInURLString(ProcessedRegField.kt:18)
        at Validator$validate$$inlined$apply$lambda$1.invokeSuspend(Validator.kt:119)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)
        at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:738)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)
Ragini
  • 765
  • 1
  • 11
  • 29

1 Answers1

-1

Java Collection classes are fail-fast, which means if the Collection will be changed while some thread is traversing over it using an iterator, the iterator.next() will throw ConcurrentModificationException, You can avoid it in your function.

fun replaceValuesInURLString(allFieldsValues: HashMap<String, UserSelectedData>, urlString: String): String {
    var result = urlString
    val iteratorValues = allFieldsValues.keySet().iterator()
    while(iteratorValues.hasNext()){
        val fieldValue = iteratorValues.next()
        val key = "$${fieldValue.key}$"
        result = result.replace(key, fieldValue.value.getDataForReg()?: "")
    }
    //Regex replace to remove query param value's which are not replaced by earlier code
    val cleanUpRegex = "(\\\$)(.*?)(\\\$)".toRegex()
    return cleanUpRegex.replace(result,"")
}