consumer producer java implementation

This is an example of a java implementation for consumer producer design pattern:

The Producer


public class Producer extends Thread {
private final int MAX_QUEUE_SIZE = 10;
private Queue queue = new LinkedList();

public void run(){
try{
while(hasMoreWork()){
//retrieve a result from somewhere
Object anObject = new Object();
//and make it available to consumer
putResult(anObject);
}
} catch(Exception e){
e.printStackTrace();
}
}

private boolean hasMoreWork(){
//TODO some check on the amount of work left for me here
return true;
}

private synchronized void putResult(Object object) throws InterruptedException {
//don't exceed max queue size
while(queue.size()>=MAX_QUEUE_SIZE){
wait();
}
//add new result to queue
queue.add(object);
notify();
}

public synchronized Object getNextResult() throws InterruptedException {
notify();
//await results
while(queue.isEmpty()){
wait();
}
//fetch next result
return queue.remove();
}

public synchronized boolean hasMoreResults() {
//see if we need to keep polling for results
return this.isAlive() || !queue.isEmpty();
}
}

The Consumer


public class Consumer extends Thread {

//a reference towards the producer
private Producer producer;

public Consumer(Producer p){
this.producer=p;
}

public void run() {
try {
//as long as producer is nog finished
while(producre.hasMoreResults()){
//fetch his results
Object result = producer.getNextResult();
//TODO do something with the results here
}
} catch ( Exception err ) {
err.printStackTrace();
}
}

}

source:
http://en.wikipedia.org/wiki/Producer-consumer_problem

Leave a Reply

Your email address will not be published. Required fields are marked *

Please reload

Please Wait