Below is my code for implementing the Producer-Consumer problem. Everything is working using notifyAll()
, however due to performance reasons, I'd like to replace all occurrences of notifyAll()
by notify()
.
I see that replacing these calls by changing notifyAll()
to notify()
causes a deadlock to happen. However, all other attempts in replacing these calls have failed.
Is there some clever way to replace these calls with notify()
that make the code below work with a single Consumer and an arbitrary number of Producers?
public class Buffer
{
private volatile String content = "";
private volatile boolean isEmpty = true;
public synchronized void addItem(String s)
{
while(!isEmpty){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
content = s;
isEmpty = false;
notifyAll();
}
public synchronized String getItem()
{
while(isEmpty) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
String temp = content;
isEmpty = true;
notifyAll();
return temp;
}
}
public class Producer implements Runnable
{
private String greeting;
private int repetitions;
private Buffer b;
public Producer(String aGreeting, int aRepetitions, Buffer aBuffer){
greeting = aGreeting;
repetitions = aRepetitions;
b = aBuffer;
}
public void run()
{
for(int i = 1; i <= repetitions; i++) {
b.addItem(greeting + i);
}
}
}
public class Consumer implements Runnable {
private String greeting;
private Buffer b;
public Consumer(String aGreeting, Buffer aBuffer){
greeting = aGreeting;
b = aBuffer;
}
public void run()
{
try
{
while(true){
System.out.println(greeting + b.getItem());
Thread.sleep(100);
}
}
catch(InterruptedException exception){}
}
}