I have a program where many threads post their requests to a PriorityQueue
.
Later, they wait for a response from ConcurrentSkipListMap
. There is ONE thread that publishes answers to the ConcurrentSkipListMap
.
The following lines of code illustrate this :
At program init
PriorityQueue<Request> requests = new PriorityQueue<Request>();
ConcurrentSkipListMap<Long, Reponse> responsesReceived = new ConcurrentSkipListMap<Long, Reponse>();
In a caller thread
// 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 ...
In THE response handler thread
// 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...
QUESTION
ConcurrentSkipListMap
?HashMap
of locks (HashMap<Long,Object>
) ? I'm pretty new with the java.util.concurrent API and I have some doubts...
While this can work, it may not be the clearest way to represent what you are doing. I would add a separate "lock" object for such notifications.
Note: I would use notifyAll() unless you only ever have one waiting thread.