Stephan
Stephan

Reputation: 43013

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

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

Upvotes: 0

Views: 304

Answers (2)

Ralf H
Ralf H

Reputation: 1474

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.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533510

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.

Upvotes: 0

Related Questions