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.


Slightly less simply, when your audio thread encounters a lock with another thread, the OS thread scheduler has to switch back and forth between them. You have little or no control over how efficiently this happens, and it can be different between OS’s, between different versions of the same OS, and even different systems.