Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: Producer = Consumer, how to know when to stop?
    primarykey
    data
    text
    <p>I have several workers, that use ArrayBlockingQueue.</p> <p>Every worker takes one object from queue, process it, and in result can get several objects, that will be put into queue for further processing. So, worker = producer + consumer.</p> <p><strong>Worker:</strong></p> <pre><code>public class Worker implements Runnable { private BlockingQueue&lt;String&gt; processQueue = null; public Worker(BlockingQueue&lt;String&gt; processQueue) { this.processQueue = processQueue; } public void run() { try { do { String item = this.processQueue.take(); ArrayList&lt;String&gt; resultItems = this.processItem(item); for(String resultItem : resultItems) { this.processQueue.put(resultItem); } } while(true); } catch(Exception) { ... } } private ArrayList&lt;String&gt; processItem(String item) throws Exception { ... } } </code></pre> <p><strong>Main:</strong></p> <pre><code>public class Test { public static void main(String[] args) throws Exception { new Test().run(); } private void run() throws Exception { BlockingQueue&lt;String&gt; processQueue = new ArrayBlockingQueue&lt;&gt;(10000); processQueue.put("lalala"); Executor service = Executors.newFixedThreadPool(100); for(int i=0; i&lt;100; ++i) { service.execute(new Worker(processQueue)); } } } </code></pre> <p><strong>Whats is the best way to stop workers, when there is no more work ?</strong></p> <p>First, what I have in mind, is to check periodically how many items in queue and how many items are currently in process. If both are equal to zero, then do something like "shutdownNow()" on ExecutorService. But I am not sure this is the best way.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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