I have the following code. Will it be thread safe even if the set itself is not thread safe?
private ConcurrentMap<REGISTRY, Set<CONTACT_ROLES>> proxyRoles = new ConcurrentHashMap<REGISTRY, Set<CONTACT_ROLES>>();
public void setProxyRoles(ConcurrentMap<REGISTRY, Set<CONTACT_ROLES>> proxyRoles) {
this.proxyRoles = proxyRoles;
}
public ConcurrentMap<REGISTRY, Set<CONTACT_ROLES>> getProxyRoles() {
return proxyRoles;
}
public synchronized void addProxyRole(REGISTRY reg, CONTACT_ROLES role) {
if(proxyRoles.get(reg) == null){
proxyRoles.put(reg, new HashSet<CONTACT_ROLES>());
}
proxyRoles.get(reg).add(role);
}
EDIT:
After some very good answers I understand that my solution would not be safe and I googled a bit and found a good replacement for my set in a ConcurrentSkipListSet
From Javadoc:
So if 2 threads are accessing the set simultaneously, they won’t acquire lock on entire set.