Can someone please review this code for me.? I have not implemented all the methods for simplicity.
Original code:
Updated code:
/**
* Implements a blocking bounded queue from a given non-blocking unbounded queue implementation
*/
abstract class DerivedQueue<E> implements Queue<E>
{
DerivedQueue(Queue<E> queue, int size)
{
if(queue==null | size <0)
{
throw new RuntimeException("Bad Input");
}
fQueue = queue;
fMaxSize = size;
}
Queue<E> fQueue;
int fMaxSize ;
int fCurrrentCnt;
@Override
public boolean isEmpty()
{
return (fCurrrentCnt==0);
}
public synchronized E remove()
{
while(fCurrrentCnt==0)
{
try
{
wait();
}
catch (InterruptedException e)
{
throw new RuntimeException("Waiting thread was interrupted during remove with msg:",e);
}
}
E elem = fQueue.remove();
fCurrrentCnt--;
notifyAll();
return elem;
}
@Override
public synchronized boolean add(E elem)
{
while(fCurrrentCnt== fMaxSize )
{
try
{
wait();
}
catch (InterruptedException e)
{
throw new RuntimeException("Waiting thread was interrupted during remove with msg:",e);
}
}
boolean bool = fQueue.add(elem);
notifyAll();
return bool;
}
}
Open questions apart from CR:
Would calling
notifyAll()lead to multiple waiting threadthreads checking thewhile()condition at the same time .., and hence there is a possibility that before the while gets saitsfiedsatisfied, 2 threads are already out of it causing an outOfBound exception?
OR Or does the methods need to be markedsynchronizedat all, and instead I can use asynchronizedblock for reading or writing part of the array while the checking of constrained and waiting can remain unsynchronized?Is theirthere a way to notify precisely only the consumer threads[waitingthreads (waiting in take]take) or only the producer[waiting input]producer (waiting input) threads in this example?
notifyAllnotifies all of them.