Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
date
Jun 2, 2022
slug
ConcurrentModificationException
status
Published
tags
Java
Bugfix
summary
type
Post
Problem
When I used
foreach-loop
and lambda
to apply a specific function to each element in a set data structure, the program threw the exception below:What’s wrong
That was because:
The for-each loop is used with both collections and arrays. It’s intended to simplify the most common form of iteration, where the iterator or index is used solely for iteration, and not for any other kind of operation, such as removing or editing an item in the collection or array.
We should avoid modifying elements in a set while iterating that set.
Solution
There are two simple ways to fix that problem:
- Use the normal
for loop
With the
for (int i...) loop
, we are not iterating the set, so we can modify the elements inside.- Synchronize the operations properly
We can use a concurrent set whose iterators won’t give the exception, such as
ConcurrentSkipListSet
.In my case, I can change my code:
to the code below: