2013-03-28 57 views
0

我有一個程序,其中許多線程將他們的請求發佈到PriorityQueue。 後來,他們等待ConcurrentSkipListMap的回覆。有一個線索發佈ConcurrentSkipListMap的答案。Java - 是否可以同步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進行同步?
  • 我應該使用鎖的HashMapHashMap<Long,Object>)嗎?

我用的java.util.concurrent API相當新的,我有些懷疑......

回答

0

雖然這可以工作,也未必代表你在做什麼,最清晰的方式。我會爲這些通知添加一個單獨的「鎖定」對象。

注:我會使用notifyAll(),除非你只有一個等待線程。

1

通過synchronized/wait/notify,您可以使用任何對象作爲鎖。至於將作業提交到隊列並等待其結果,請參閱ExcutorServiceFutureCompletionService

+0

+1因爲使用ExecutorService很可能是更好的解決方案。 – 2013-03-28 10:13:19