2

I have implemented a producer consumer problem using BlockingQueue. In this, producer post some tasks at different interval to blocking queue and multiple consumers take that task to process it. My producer code is working fine but my consumer object is throwing error. I am really new to multithreading. I shall be thankful for help.

Producer

public class Producer_Events implements Runnable{

private BlockingQueue<ArrayList<String>> queue;
ArrayList<String> batch_list = new ArrayList<String>();

public Producer_Events(BlockingQueue<ArrayList<String>> queue,ArrayList<String> batch_list) {
    this.queue = queue;
    this.batch_list = batch_list;

}

public void run() {
    try {
        // do all the shit
        ArrayList<Long> tymstamp = new ArrayList<Long>();
        // read timestamp from a file and as per timestamp put value in blockingqueue
        //if timestamp ended put a variable named poison to terminate the thread for both producer and consumer
        System.out.println("Timestamp added");
        for (int m = 0; m<batch_list.size();m++){

            String operator = new String();
            operator = batch_list.get(m);
            ArrayList<String> batch1 = new ArrayList<>();
            Thread.sleep(100);// timestamp to add value in blockqueu
            batch1.add(operator);
            if(m!=batch_list.size()){
                queue.put(batch1);
                System.out.println("Event Added: "+ m);
            }
            else{
                // inject a poison
                ArrayList<String> batch2 = new ArrayList<>(-1);
                queue.put(batch2);
                System.out.println("Producer STOPPED.");
            }

        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
}}

Consumer Code

public class ConsumerWorker implements Runnable {

private BlockingQueue<ArrayList<String>> inputQueue;

// private final static ArrayList<String> POISON = new ArrayList<String>();

public ConsumerWorker(BlockingQueue<ArrayList<String>> inputQueue) {
    this.inputQueue = inputQueue;
}

@Override
public void run() {
    // worker loop keeps taking en element from the queue as long as the
    // producer is still running or as
    // long as the queue is not empty:
    System.out.println("Check loop");
    while (true) {
        System.out.println("Consumer " + Thread.currentThread().getName()
                + " START");
        try {
            ArrayList<String> queueElement = inputQueue.take();
            System.out.println("Event Send to Crowd: ");
            if (queueElement.isEmpty()) {
                break;
            } else {

                System.out.println("DO Processing");

            }

        } catch (InterruptedException e) {
            System.out.println("Interrupted.");
        }
        System.out.println("Throwing exception ...");
        throw new RuntimeException();
    }
}}

MAIN FUnction

public class test {

/**
 * @param args
 */
public static void main(String[] args) {

    ArrayList<String> batch_list = new ArrayList<>();
    for (int i=0;i<10;i++){
        batch_list.add("OK");
    }
    // block queue of size 20
    BlockingQueue<ArrayList<String>> queue = new ArrayBlockingQueue<ArrayList<String>>(20);
    // creating multiple consumers to access blockqueue
    ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);

    Producer_Events producer = new Producer_Events(queue,batch_list);
    ConsumerWorker consumer = new ConsumerWorker(queue);
    System.out.println("OK");
    new Thread(producer).start();
    executor.execute(consumer);

    /*Thread myThread = new Thread(new ConsumerWorker(queue));

    //ConsumerWorker consumer = new ConsumerWorker(queue);
    myThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread myThread, Throwable e) {
            System.out.println(myThread.getName() + " throws exception: " + e);
         }
    });*/

}}

ERROR enter image description here

Piyush
  • 388
  • 1
  • 6
  • 21
  • 1
    private final static ArrayList POISON = new ArrayList( -1); //this should not be -1 I found this one but if this is not the case it will be helpful if you share exception details. – cody123 Mar 02 '17 at 06:53
  • When you write not initialized can you provide more details? Is an exception raised? What output proves your assertion? – Adonis Mar 02 '17 at 07:51
  • Hint: read about java naming conventions: you do **not** use "_" in names; unless for SOME_CONSTANTS. Seriously; reading your code gives me the creeps. That makes it 10 times harder to read your code than it ought to be. – GhostCat Mar 02 '17 at 08:47
  • And talking about naming: POISON is absolutely misleading. I took me again much more time as necessary to understand that POISON could have been named DUMMY_QUEUE_ENTRY_TO_STOP_CONSUMER or something alike. And just for the record: most people would not insert a special constant into the queue to stop the consumer, but simply have a `while(active)` loop; using some `private volatile boolean active` to be used by your setter method. – GhostCat Mar 02 '17 at 08:53
  • @GhostCat... srry for late response... i tried to catch exceptions but unable to find any stack trace. I used setUncaughtExceptionHandler . I reallly dont know what I am missing in Consumer class. Will be thankful if u can suggest how to catch error if thread object initialisation fails. – Piyush Mar 02 '17 at 12:15
  • As said: step back and see if you can create a **full** [mcve]. A piece of code that we worst case can copy/paste and **run** on our end to repro the problem. Alone the process of building that example will often enough solve the puzzle for you while doing it (therefore it is such an important skill to be able to reduce your problem to as-simple-as-possible code) – GhostCat Mar 02 '17 at 12:17
  • @GhostCat... fully working minimal ,complete,verifiable example – Piyush Mar 02 '17 at 13:10
  • Kewl. I can't promise that I have the time to look into this (now); but at least your question is in much better shape than before! – GhostCat Mar 02 '17 at 13:20
  • I am stupid.... seriously... I have found answer... that was poison.. which was making error.. thanks for help... Here I am also stupid posting you a problem throwing runtime error.... Seriously I should sleep.. – Piyush Mar 02 '17 at 13:24

0 Answers0