I have an object called Cursor. It has a value in it that gets incremented.
I have a HashSet called Cursors. When the Cursor reaches a target, I want to delete it from the HashSet. But I’m running into Concurrency errors.
The code fragment below (a “for” loop) runs repeatedly in yet another encasing loop.
First try
for (Cursor c : cursors)
{
newValue = c.increment();
if (newValue > target) cursors.remove(c);
}
Second try, I made a second HashSet called “removalSet”
for (Cursor c : cursors)
{
newValue = c.increment();
if (newValue > target) removalSet.add(c);
}
for (Cursor c : removalSet)
{
cursors.remove(c);
}
removalSet.clear();
I am fairly confident this second version is fine, but I did get one concurrency exception in about 40 playbacks, at the first “for” loop. There was another error also made in that run that maybe could have been the real cause of the exception.
Should #2 be OK? Is there a better way to do this? Perhaps another collection option? I see that there is a ConcurrentHashMap, but I don’t think I should have to add the complication of dealing with keys & values.