简体   繁体   English

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

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

I have a program where many threads post their requests to a PriorityQueue . 我有一个程序,其中许多线程将其请求发布到PriorityQueue Later, they wait for a response from ConcurrentSkipListMap . 稍后,他们等待来自ConcurrentSkipListMap的响应。 There is ONE thread that publishes answers to the ConcurrentSkipListMap . 有一个线程发布对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 ? ConcurrentSkipListMap上同步调用者线程和响应处理程序线程是否安全?
  • Should I rather use a Lock for the synchronization ? 我应该使用Lock进行同步吗?
  • Should I use a HashMap of locks ( HashMap<Long,Object> ) ? 我应该使用HashMap的锁( HashMap<Long,Object> )吗?

I'm pretty new with the java.util.concurrent API and I have some doubts... 我对java.util.concurrent API相当陌生,我对此有些怀疑。

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 . 至于将作业提交到队列中并等待其结果,请看一下ExcutorServiceFutureCompletionService

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. 注意:除非您只有一个等待线程,否则我将使用notifyAll()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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