Java - 在ConcurrentSkipListMap上同步线程是否可以接受?

时间:2013-03-28 10:07:26

标签: java multithreading concurrentskiplistmap

我有一个程序,许多线程将他们的请求发布到PriorityQueue。 之后,他们等待ConcurrentSkipListMap的回复。有一个帖子可以发布ConcurrentSkipListMap的答案。

以下代码行说明了这一点:

在程序初始化

PriorityQueue<Request> requests = new PriorityQueue<Request>();
ConcurrentSkipListMap<Long, Reponse> responsesReceived = new ConcurrentSkipListMap<Long, Reponse>();

在来电线程中

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

在响应处理程序线程中

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

问题

  • ConcurrentSkipListMap
  • 上同步调用者线程和响应处理程序线程是否安全?
  • 我是否应该使用Lock进行同步?
  • 我应该使用HashMap锁(HashMap<Long,Object>)吗?

我是java.util.concurrent API的新手,我有些疑惑......

2 个答案:

答案 0 :(得分:1)

使用synchronized / wait / notify,您可以将任何对象用作锁定。至于将作业提交到队列并等待其结果,请查看ExcutorServiceFutureCompletionService

答案 1 :(得分:0)

虽然这可行,但它可能不是表达您正在做的事情的最明确方式。我会为这些通知添加一个单独的“锁定”对象。

注意:除非你只有一个等待线程,否则我会使用notifyAll()。