Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>A:</strong> There is simply no guarantee that just because <code>peek</code> returns <code>null</code>, the producer has stopped producing. What if the producer simply got slowed down? Now, the consumer quits, and the producer keeps producing. So the 'peek' -> 'break' idea basically fails.</p> <p><strong>B:</strong> Setting a 'done/run' flag from consumer and reading it in producer also fails, if:</p> <ol> <li>consumer checks the flag, finds it should keep running, then does a 'take'</li> <li>in meanwhile, producer was setting the flag to 'dont run'</li> <li>Now consumer blocks forever waiting for a ghost packet</li> </ol> <p>The opposite can also happen, and one packet gets left out un-consumed.</p> <p>Then to get around this, you will want to do additional synchronization with mutexes over and above the 'BlockingQueue'.</p> <p><strong>C:</strong> I find 'Rosetta Code' to be fine source of deciding what is good practice, in situations like this:</p> <p><a href="http://rosettacode.org/wiki/Synchronous_concurrency#Java">http://rosettacode.org/wiki/Synchronous_concurrency#Java</a></p> <p>The producer and consumer must agree upon an object (or an attribute in the object) that represents end of input. Then the producer sets that attribute in the last packet, and the consumer stops consuming it. i.e. what you referred to in your question as 'poison'.</p> <p>In the Rosetta Code example above, this 'object' is simply an empty <code>String</code> called 'EOF':</p> <pre><code>final String EOF = new String(); // Producer while ((line = br.readLine()) != null) queue.put(line); br.close(); // signal end of input queue.put(EOF); // Consumer while (true) { try { String line = queue.take(); // Reference equality if (line == EOF) break; System.out.println(line); linesWrote++; } catch (InterruptedException ie) { } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload