[concurrency-interest] BlockingQueue.drainTo question

Richard Zschech richard.zschech at mnetcorporation.com
Mon Jul 24 01:28:45 EDT 2006


Hi,

I was wondering why BlockingQueue.drainTo doesn't block when there is 
nothing in the queue.

I am trying to write a basic producer / consumer program where the 
consumer most efficiently processes batches of objects at a time. I was 
hoping to use the drainTo method to extract a batch of objects to 
process for example:

    private BlockingQueue<Message> messages;

    public void run() {
        List<Message> batch = new ArrayList<Message>(BATCH_SIZE);
       
        while (run) {
            messages.drainTo(batch, BATCH_SIZE);
           
            for (Message message : batch) {
                System.out.println(message);
            }
           
            batch.clear();
        }
    }

The only solution I can think of is to insert 
"batch.add(messages.take())" which will block before a drainTo(batch, 
BATCH_SIZE-1) which will extract the rest of the batch.

Does this sound correct?
Is there a better way of doing this?

Thanks in advance,
 From Richard.


More information about the Concurrency-interest mailing list