This should be a fairly common occurrence when I have a card and you want to safely copy your keyring set:
public MyClass { Map<String,String> map =
Now, if my "card" is not thread safe, it is unsafe:
public final Set<String> keys() { return map.keySet(); }
And no:
public final Set<String> keys() { return Collections.unmodifiableSet(map.keySet()); }
Therefore, I need to create a copy, for example:
public final Set<String> keys() { return new HashSet(map.keySet()); }
However, this does not look safe, as this constructor bypasses the parameter elements and adds () s them. Thus, while this copying is in progress, a ConcurrentModificationException may occur.
So then:
public final Set<String> keys() { synchronized(map) { return new HashSet(map.keySet()); } }
seems like a solution. Does this look right?
source share