【发布时间】:2011-12-13 22:05:43
【问题描述】:
我有以下用于带同步方法的路由器表的类:
public class RouterTable {
private String tableForRouter;
private Map<String,RouterTableEntry> table;
public RouterTable(String router){
tableForRouter = router;
table = new HashMap<String,RouterTableEntry>();
}
public String owner(){
return tableForRouter;
}
public synchronized void add(String network, String ipAddress, int distance){
table.put(network, new RouterTableEntry(ipAddress, distance));
}
public synchronized boolean exists(String network){
return table.containsKey(network);
}
}
多个线程将读取和写入 HashMap。我想知道是否最好删除方法上的同步并只使用 Collections.synchronizedMap(new HashMap
【问题讨论】:
-
取决于,真的,因为还有一个使用
ConcurrentHashMap的选项,它是 Java 并发的一部分:stackoverflow.com/questions/510632/… 和 ibm.com/developerworks/java/library/j-jtp08223
标签: java dictionary collections thread-safety synchronized