Search code examples
javamultithreadingconcurrentskiplistmap

Java - Is it acceptable to synchronize threads on a ConcurrentSkipListMap?


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...


Solution

  • 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.