0

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

  • Is it safe to synchronize caller threads and response handler thread on the ConcurrentSkipListMap ?
  • Should I rather use a Lock for the synchronization ?
  • Should I use a HashMap of locks (HashMap<Long,Object>) ?

I'm pretty new with the java.util.concurrent API and I have some doubts...

2 Answers 2

1

With synchronized/wait/notify, you can use any object as lock. As for submitting jobs to a queue and waiting for their results, take a look at ExcutorService, Future, and CompletionService.

1
  • +1 As using an ExecutorService is likely to be a better solution. Mar 28, 2013 at 10:13
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.