How to avoid ConcurrentModificationException in co...
# announcements
m
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
No, because the array is not affected by further edits of the map.
m
Yeah but does
toTypedArray()
iterates over the collection in a way that could be affected by modification of the collection/map?
b
could you use a
ConcurrentHashMap
instead?
l
If you are modifying on another thread, you would still risk this, and you need to use what Brian suggested (
ConcurrentHashMap
).
z
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.
125 Views