I have a Java 1.8 class that holds two collections:
Map<Key,Object>
Set<Object>
My class five methods:
addObjectToMap()
removeObjectFromMap()
addObjectToSet()
removeObjectFromSet()
loopOverEverything(){
for(Object o : mySet){
for(Object o2 : myMap.getKeySet()){
doSomething(o,o2);
}
}
}
The point of the class is to implement the observer pattern but be very flexible in both observers and observees. The problem I face is that the last method can easily throw a ConcurrentModificationException when a thread calls the add/remove methods while the looping is going on. I was thinking about synchronizing all methods on "this":
set.add(object);
would become
synchronized(this){
set.add(object);
}
and I would add a similar synchronize statement to the other 4 methods, including the loop method.
Will this work? I know synchronizing methods can cause bottlenecks. Even though there is currently no performance issue, I would like to rationalize this design and hear about possible alternatives that have less of a performance hit.
Collections.synchronizedSetdoesn't hold a lock during iteration, so you can still getConcurrentModificationExceptionfairly easily.