2015-12-21 81 views
0

考慮以下行的LinkedBlockingQueue下同步嵌套,活鎖問題

public Result doSomething(Service srv) throws InterruptedException 
{ 
    synchronized(srv) 
    { 
     if (this._registeredServices.containsKey(srv.getId())) 
     { 
      return this._queue.get(srv.getId()).take(); 
     } 
     throw new IllegalStateException(); 
    } 
} 

其中this._queue

private ConcurrentHashMap<String, LinkedBlockingQueue<Result>> _queue; 

幾個線程正在使用的同步過程的訪問來自不同的地方srv實現。

我的問題是,我可以進入livelock wheras take方法正在等待數據並仍然保持srv鎖,或者它釋放它直到它有一個值,然後嘗試重新抓住它繼續之前?

回答

2

srv上的鎖定未在同步塊內的任何位置釋放。 LinkedBlockingQueue不知道它存在的任何內容,並且對此無能爲力。如果take()阻塞,則使用相同srv調用的另一個線程將阻塞synchronized(srv)。儘管如此,它也會阻止take()

該代碼看起來不必要的複雜的方式。