multithreading - Can I implement blocking queue with two objects serving as locks in Java? -


i trying understand java's synchronized keyword, wait(), , notify() implementing blocking queue class. 1 of blocking queue implementation described this article. wonder if possible use 2 objects serving lock implement blocking queue? below code correct?

public class blockingqueue {   private list<object> queue = new linkedlist<object>();   private int limit;   private object slots = new object();   private object objs = new object();   public blockingqueue(int limit) {     this.limit = limit;   }   private synchronized void enqueue(object o)    throws interruptedexception {     if (queue.size() == limit)       slots.wait();     objs.notify();     queue.add(o);   }   private synchronized object dequeue()   throws interruptedexception {     if (queue.size() == 0)       objs.wait();     slots.notify();     return queue.remove(0);   } } 

first of all, cannot wait or notify on object didn't synchronized on. here use this.wait() , this.notifyall.

second, should never wait() once without rechecking condition. whatever put in 'if' should in while loop; because notified mistake without condition having changed, since using monitor on instance outside can synchronize , notify on. should rather use synchronized(privatelockobject) {}.

this leads question, can synchronize 2 + objects... yes, nesting synchronized blocks, lead hanging code, since wait() call free 1 monitor waited on, not outer monitor. therefore pointless.

if trying avoid notifying both readers , writers waiting on queue, honorable thought, cannot synchronized. example cited doing single monitor, , why must use notifyall() instead of notify(), because want make sure wake proper thread waiting. have use reentrantlock 2 distinct conditions (not empty, , not full).


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -