Error de cola completa, trabajando con varios consumidores, productores

I would like to simulate the following scenario: Multiple consumers, producer threads working on modifying some data as

Preparar

    BlockingQueue<String> q1 = new SynchronousQueue<String>();
    BlockingQueue<String> q2 = new SynchronousQueue<String>();

    Producer dataProducer = new Producer(q1); // publish to q1

    Filter1 filter1 = new Filter1(q1, q2);    // read from q1, publish to q2
    Filter2 filter2 = new Filter2(q2);        // read from q2

    new Thread(dataProducer, "Producer-Thread").start();
    new Thread(filter1, "Filter1-Thread").start();
    new Thread(filter2, "Filter2-Thread").start();

Productor

public void run() {
    try {
        while (true) {
            this.q.put(saySomething());
        }
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
}

public String saySomething() {
    return "Something";
}

Filtro 1

public void run() {
    try {
        while (true) {
            consume(qIn.take());
        }
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
}

private void consume(String take) {
    //Modify data according to some rules
    String newData = take.replace("m", "-");
    produce(newData);
}

private void produce(String newData) {
    // put new data in queue out
    qOut.add(newData);                   // <-- Stacktrace points here
}

Filtro 2

public void run() {
    try {
        while (true) {
            consume(qIn.take());
        }
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
}

private void consume(String s) {
    System.out.println("Something became: " + s);
}

So, to recap: Producer puts something in a queue from which Filter 1 reads. It modifies the data and publishes it to another queue from which Filter 2 reads. Filter 2 prints the final data.

This code fails with

Exception in thread "Thread-2" java.lang.IllegalStateException: Queue full

Could you please help me understand why?

preguntado el 01 de febrero de 12 a las 03:02

1 Respuestas

Deberías estar usando put() y no add() A SynchronousQueue is always full and empty, it has no depth. put() will tell the queue to suspend this thread until another thread comes in to take the element off the queue.

El add() method will only succeed if there is a thread waiting, if no thread is waiting you will get the Queue Full exception.

Respondido 01 Feb 12, 07:02

Brilliant! Thank you so very much John - James Raitsev

Sad!! I can only upvote once.. but, wish to give more.. My code ran fine with windows with add(), but gave queue full.. in linux.. Wt a silly thing I have done :( - Thanks John. - Presagio

@John why it was fine with windows and not with linux? Do u have any idea? - Presagio

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.