So I have written a bounded buffer problem in java using monitors and I can't figure out whats wrong with my program. sometimes it keeps running in an infinite loop just before the end of the third loop. Most of the times it runs perfectly. the program is simple and about one producer and multiple consumers. I would appreciate any help. here is a link to my github where you can find the whole code. the full code
BoundedBuffer
public class BoundedBuffer {
public BoundedBuffer ()
{
int numWorms = 10;
int numBirds = 5;
Dish dish = new Dish (numWorms);
Parent parent = new Parent(dish);
parent.start();
Child child[] = new Child[numBirds];
for (int i = 0; i < numBirds; i++)
{
child[i] = new Child (dish);
child[i].start();
}
for (int i = 0; i < numBirds; i++)
{
try {child[i].join();}
catch (Exception ie) {System.out.println (ie.getMessage());}
}
System.out.println("bids done eating :D");
}
}
Dish
public class Dish
{
int worms;
int copy;
public Dish (int worms)
{
this.worms = worms;
copy = worms;
}
public synchronized void eat ()
{
if (worms <= 0)
{
waitForFull();
}
worms --;
System.out.println("Bird " + Thread.currentThread().getName() + " has
eaten."
+ " The number of worms left is " + worms);
}
public synchronized void fill()
{
if (worms > 0)
{
waitForEmpty();
}
worms = copy;
System.out.println ("Parent filled the dish");
notifyAll();
}
public synchronized void waitForEmpty ()
{
while (worms > 0)
{
notifyAll();
try {wait();}
catch (Exception ie) {System.out.println (ie.getMessage());}
}
}
public synchronized void waitForFull ()
{
while (worms <= 0)
{
notifyAll();
try {wait();}
catch (Exception ie) {System.out.println (ie.getMessage());}
}
}
}
I can not repoduce the
stucksituation. But I found some other problems in your code:Parentsetdone = 1immediatlly after three loops, at this time, there are stillWormsin theDish.waitForEmptyandfillare not automatic, which may result in some inconstency.waitForFullandeatare not automatic, which may result in some inconstency.Two solve these problems, I think you need:
waitForEmptyandfillas a single method, as well aswaitForFullandeat.shutdownandisTerminateas signal.ParentwillshutdowntheDish, while the lastChildwillterminatetheDish.Here is the code:
Main
BoundedBuffer
Dish
Parent
Child
OutPut: