我需要使用某種數據結構來存儲掛起的網絡請求。java:用於存儲未決網絡請求的線程安全數據結構(隊列+映射)?
理想情況下,我想隊列也提供地圖訪問,因爲操作基本上如下:
interface PendingRequestStore<K, V>
{
/* add item to queue with value v and key k */
void add(K k, V v);
/* remove and return value of first item in queue, or null if empty */
V pollFirst();
/* return the key of the first item in the queue, or null if empty */
K getFirstKey();
/* get item with key k, or null if absent */
V get(K k);
/* remove and return value of item in queue with key k, or null if absent */
V remove(K k);
}
的目的是爲了存儲掛起的請求時,他們被髮送出去;那麼,當我得到響應時,我可以使用指定的鍵移除請求。答覆一般不會按請求發出的順序到達。如果我能保證及時回覆,那麼經常使用Map
就足夠了,但偶爾也會出現故障,我還需要按照添加到隊列中的順序重新發送孤兒請求。所以我會使用隊列和一張地圖,但是當我收到亂序響應時,我需要一種方法來刪除隊列中間的項目。
如果我無法避免同步,那也沒問題,但是也可以使用併發數據結構。
有什麼建議嗎?
注:這些鍵沒有順序使一個有序圖如ConcurrentSkipListMap
不會幫助我。
查看'java.util.concurrent'包中的集合類。 – 2011-04-27 15:28:48
?哪個?我很熟悉w/j.u.c,並且在這種情況下它們都沒有明顯可用。 – 2011-04-27 15:30:42
舊的LinkedHashMap有什麼問題,Map m = Collections.synchronizedMap(new LinkedHashMap(...))'? – davin 2011-04-27 15:37:36