https://kotlinlang.org logo
#announcements
Title
# announcements
m

Marko Mitic

08/05/2019, 7:03 PM
How to avoid ConcurrentModificationException in concurrent code when iterating Map's values? Any safe API for this?
Does
toTypedArray()
throw if collection is mutated during the call?
l

louiscad

08/05/2019, 7:20 PM
No, because the array is not affected by further edits of the map.
m

Marko Mitic

08/05/2019, 7:40 PM
Yeah but does
toTypedArray()
iterates over the collection in a way that could be affected by modification of the collection/map?
b

bbaldino

08/05/2019, 7:42 PM
could you use a
ConcurrentHashMap
instead?
l

louiscad

08/05/2019, 7:51 PM
If you are modifying on another thread, you would still risk this, and you need to use what Brian suggested (
ConcurrentHashMap
).
z

zokipirlo

08/06/2019, 7:15 AM
With multiple threads it would be smart to synchronize work. When iterating over map, store keys which need to be removed in a list and do that after iteration. That how you prevent modification while iterating.
111 Views