Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>PriorityBlockingQueue does not seem to make sense in your case since you simply want to process the messages in their original order.</p> <p>If you really want to handle the queue yourself, you can use a bounded LinkedBlockingQueue:</p> <pre><code>//example with a limit of 100,000 messages being in the queue at any one time private static final BlockingQueue&lt;Message&gt; queue = new LinkedBlockingQueue&lt;&gt; (100_000); </code></pre> <p>In the producer you keep doing:</p> <pre><code>Message msg = getMessage(); queue.put(msg); //blocks if the queue is full </code></pre> <p>and in the consumer:</p> <pre><code>Message msg = queue.take(); //blocks until there is a message </code></pre> <hr> <p>Peter Lawrey's alternative consists in doing:</p> <pre><code>private static final ExecutorService executor = Executors.newFixedThreadPool(10); </code></pre> <p>in your producer:</p> <pre><code>final Message msg = getMessage(); Runnable task = new Runnable() { public void run() { process(msg); } } executor.submit(task); </code></pre> <p>And there is no comsumer since your producer has created it (the task).</p> <hr> <p>Note: In the threadpool example, I used a size of 10 threads based on the assumption that the <code>process</code> method is mostly CPU-bound and you have around 10 processors. In practice:</p> <ul> <li>if it is the case (CPU-bound), you would use <code>Runtime.getRuntime().availableProcessors()</code> to get the number of processors instead of a harcoded number.</li> <li>if not (I/O bound) you would use more threads - the optimal number is difficult to estimate beforehand and you would need to profile you app with different numbers to find the optimal value.</li> </ul>
 

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