0

I am trying to implement a small producer-consumer example in Java using ExecutorService.

Here is my main class

class Example {
  public static void main(String args[]) {
         BlockingQueue<String> queue = new ArrayBlockingQueue<>(1000);
    Producer producer = new Producer(queue);
    Consumer consumer = new Consumer(queue);
    ExecutorService executor = Executors.newCachedThreadPool();
//    executor.execute(consumer);
    Future producerFuture = executor.submit(producer);
    Future consumerFuture = executor.submit(consumer);
    try {
      producerFuture.get();
      consumerFuture.get();
    } catch (InterruptedException e) {
      LOG.error("Failed");
    }
    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.MILLISECONDS);
  }
}

Producer Class

public class Producer implements Runnable {
  private BlockingQueue<String> queue;
  public Producer(BlockingQueue<String> queue) {
    this.queue = queue;
  }

  @Override
  public void run() {
    for (int i = 0; i < 10; i++) {
      try {
        queue.put(i + "HELPPPPP");
      } catch (InterruptedException ex) {
        Logger.getLogger(MigrationToolProducer.class.getName()).log(Level.SEVERE, null, ex);
      }
    }

Consumer Class

public class Consumer implements Runnable {
  private final BlockingQueue<String> queue;
    private volatile boolean keepRunning = true;

  public Consumer(BlockingQueue<String> queue) {
    this.queue = queue;
  }

  @Override
  public void run() {
     while (keepRunning) {
      String value;
      try {
        value = queue.take();
      } catch(InterruptedException e) {
        throw new RuntimeException(e);
      }
       System.out.println(value);
    }
  }
}

EDIT The execution is stuck at queue.take() in Consumer Class. Can anyone please help me fix this problem ? Why is the execution stuck in the consumer ?

Newbie
  • 2,664
  • 7
  • 34
  • 75
  • 1
    Why do you think it should not be _stuck_ there? What part of your code lets your `Consumer` `Runnable` complete and complete the corresponding `Future`? – Sotirios Delimanolis Aug 18 '16 at 00:37
  • Can you please explain ? Also, when I increase the objects I put in Producer to 100, I dont get all the 100 items printed. A random number of items are printed and it is stuck. I know I am not changing keepRunning to false but I dont know for what condition I have to make it false. – Newbie Aug 18 '16 at 00:43

1 Answers1

0

One possible solution:

1) On Producer side, put a "END" signal after original 10 puts:

queue.put("END");

2) On Consumer side, once detect "END" signal, break the loop:

public void run() {
while (keepRunning) {
  String value;
  try {
    value = queue.take();
    if(value.equals("END")) {
       System.out.println("Get END signal. All done!");
       break;
    }
  } catch(InterruptedException e) {
    throw new RuntimeException(e);
  }
  System.out.println(value);
}

}

yuanli123
  • 1
  • 1