比方說,我有一個HashMap聲明如下:正確HashMap的同步
@GuardedBy("pendingRequests")
private final Map<UInt32, PendingRequest> pendingRequests = new HashMap<UInt32, PendingRequest>();
訪問地圖是多線程的,並且所有的訪問是通過同步在地圖上的最後實例,如守衛:
synchronized (pendingRequests) {
pendingRequests.put(reqId, request);
}
這夠了嗎?地圖是否應該使用Collections.synchronizedMap()
創建?我應該鎖定一個專用鎖對象而不是地圖實例嗎?或者兩者兼得?
需要在地圖上多次調用必須爲原子的幾個區域外部同步(除了可能使用Collections.synchronizedMap()
之外)。
@KevinHerron爲什麼不使用['ConcurrentHashMap'](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html)? – 2012-03-01 20:27:13