I'm working on a producer/consumer pattern, my producer should wait the answer that can be a result object or an exception. What is the best way to do so? I read many examples of this pattern but every time the producer never minds about a return value or of a consumer exception.
public class BlockingQueueExample {
public static void main(String[] args) throws Exception {
BlockingQueue queue = new ArrayBlockingQueue(1024);
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);
new Thread(producer).start();
new Thread(consumer).start();
Thread.sleep(4000);
}
}
public class Producer implements Runnable{
protected BlockingQueue queue = null;
public Producer(BlockingQueue queue) {
this.queue = queue;
}
public void run() {
try {
queue.put(new Job("test"));
//here I need the job result or exception
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Consumer implements Runnable{
protected BlockingQueue queue = null;
public Consumer(BlockingQueue queue) {
this.queue = queue;
}
public void run() {
while(true){
queue.take();
try{
// ... my job
Result obj;
// I have to return to producer the result!
}catch(Exception e){
//In case of exception I have to return the exception to the producer.
}
}
}
}
MIND: there can be more than one Producer and Consumer.
My only option now is to use a Queue with this object:
public class Job{
private String input;
private Exception exception;
private String result;
public Jon(String input){
this.input=input;
this.exception=null;
}
public void setException(Exception exception){
this.exception=exception;
}
public Exception getException(){
return this.exception;
}
public void setResult(String result){
this.result=result;
}
public Exception getResult(){
return this.result;
}
}
and let the procuder read back its result or the exception. Otherwise should I use a BlockingQueue of FutureTask?