For the below function, I am trying to return a new Set mHashSet that is a copy of another set iGraphicSectors:
public Set<String> getGraphics() {
synchronized (iGraphicSectors) { // class variable of type Set<String>
LinkedHashSet<String> mHashSet = new LinkedHashSet<String>();
synchronized (mHashSet) {
mHashSet.addAll(iGraphicSectors);
}
return mHashSet;
}
}
However line 5 mHashSet.addAll(iGraphicSectors); is throwing a ConcurrentModificationException (I am not sure how this is possible). Is there a way I can accomplish the above task in a thread-safe manner?
iGraphicSectorsto wrap it in asynchronized (iGraphicSectors), or changeiGraphicSectorsto be class that is thread safe for iteration.mHashSetis unnecessary. There is no way, that any other thread could have a reference to that newly created set instance.mHashSet, and haven't shared it with anyone, there is no reason whatsoever for usingsynchronized (mHashSet).mHashSetaccomplishes nothing because no other thread can possibly access the new object before your method returns.