我有一個程序,其中許多線程將他們的請求發佈到PriorityQueue
。 後來,他們等待ConcurrentSkipListMap
的回覆。有一個線索發佈ConcurrentSkipListMap
的答案。Java - 是否可以同步ConcurrentSkipListMap上的線程?
的下面幾行代碼說明這一點:
在程序初始化
PriorityQueue<Request> requests = new PriorityQueue<Request>();
ConcurrentSkipListMap<Long, Reponse> responsesReceived = new ConcurrentSkipListMap<Long, Reponse>();
在調用程序線程
// Send request ...
Request r = ... // Elaborate the request
requests.add(r);
// ... then wait for an answer
Long id = r.getId();
while (responsesReceived.containsKey(id) == false) {
synchronized (responsesReceived) {
responsesReceived.wait();
}
}
Answer a = responsesReceived.take(id);
// Do other things ...
在響應處理線程
// Wait for a remote answer
Answer answer = ...;
// Once received publish it in ConcurrentSkipListMap
responsesReceived.put(answer.getRequestId(), answer);
synchronized (responsesReceived) {
responsesReceived.notify();
}
// Go back and wait for a new answer...
問題
- 它是安全的同步上
ConcurrentSkipListMap
呼叫者線程和響應處理線程? - 我是否應該使用Lock進行同步?
- 我應該使用鎖的
HashMap
(HashMap<Long,Object>
)嗎?
我用的java.util.concurrent API相當新的,我有些懷疑......
+1因爲使用ExecutorService很可能是更好的解決方案。 – 2013-03-28 10:13:19