我有一个程序,其中许多线程将他们的请求发布到PriorityQueue
. 稍后,他们等待来自 的回应ConcurrentSkipListMap
。有一个线程发布对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 进行同步吗?
- 我应该使用 a
HashMap
of locks (HashMap<Long,Object>
) 吗?
我对 java.util.concurrent API 很陌生,我有一些疑问......