I'm learning to implement producer consumer problem using wait and notify methods. I'm using a linked list, and set limit to 20 items for the list. Below is the code:
import java.util.LinkedList;
import java.util.Random;
public class ProducerConsumer {
private static final int MAX_SIZE = 10;
LinkedList<Integer> queue = new LinkedList<Integer>();
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();
Thread prod = new Thread(new Producer(pc.queue));
Thread cons = new Thread(new Consumer(pc.queue));
prod.start();
cons.start();
}
}
class Producer implements Runnable {
// Produce until queue is full.
private LinkedList sharedQueue;
Producer(LinkedList sharedQueue) {
this.sharedQueue = sharedQueue;
}
public void run() {
while (true) {
synchronized (sharedQueue) {
System.out.println("size : " + sharedQueue.size());
while (sharedQueue.size() >= 20) {
try {
sharedQueue.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Random random = new Random();
int i = random.nextInt();
System.out.println("Produced: " + i);
sharedQueue.add(i);
sharedQueue.notifyAll();
}
}
}
}
class Consumer implements Runnable {
// Produce until queue is full.
private LinkedList sharedQueue;
Consumer(LinkedList sharedQueue) {
this.sharedQueue = sharedQueue;
}
public void run() {
while (true) {
synchronized (sharedQueue) {
while (sharedQueue.isEmpty()) {
try {
sharedQueue.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Element consumed : " + sharedQueue.removeFirst());
sharedQueue.notifyAll();
}
}
}
}
As evident, when the queue size is greater than or equal to 20 (though I doubt that greater condition is even needed), I make the producer thread wait. Also, I printed the size for the list while producing and I never get it greater than 20 in the logs. Still, when I run the above program, I get Java heap space error. Any help would be appreciated on how to modify the above program to work.