简体   繁体   中英

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM