我需要保持多个值的轨道对唯一的密钥,即1(A,B)图2(c,d)等...java.util.concurrent中:外部同步以去除映射值
的解决方案是由多个线程有效地访问我有以下定义;
ConcurrentSkipListMap<key, ConcurrentSkipListSet<values>>
我的问题是当值集大小为0时删除键是否需要同步?我知道这两个类是“并发”的,我查看了OpenJDK的源代码,但是我看到在一个线程T1之间出现一个窗口,检查Set是否为空,并删除了remove(...)另一个线程T2调用add(...)。结果是T1删除最后一个Set条目并删除与T2交错的Map,只是添加一个Set条目。因此,Map和T2 Set条目被T1删除,数据丢失。
我只是“同步”add()和remove()方法,还是有“更好”的方法?
该地图由多个线程修改,但只能通过两种方法修改。
代码片段如下;
protected static class EndpointSet extends U4ConcurrentSkipListSet<U4Endpoint> {
private static final long serialVersionUID = 1L;
public EndpointSet() {
super();
}
}
protected static class IDToEndpoint extends U4ConcurrentSkipListMap<String, EndpointSet> {
private static final long serialVersionUID = 1L;
protected Boolean add(String id, U4Endpoint endpoint) {
EndpointSet endpoints = get(id);
if (endpoints == null) {
endpoints = new EndpointSet();
put(id, endpoints);
}
endpoints.add(endpoint);
return true;
}
protected Boolean remove(String id, U4Endpoint endpoint) {
EndpointSet endpoints = get(id);
if (endpoints == null) {
return false;
} else {
endpoints.remove(endpoint);
if (endpoints.size() == 0) {
remove(id);
}
return true;
}
}
}