How to block until a BlockingQueue is empty?

前端 未结 6 2093
逝去的感伤
逝去的感伤 2021-02-02 10:30

I\'m looking for a way to block until a BlockingQueue is empty.

I know that, in a multithreaded environment, as long as there are producers putting items in

6条回答
  •  时光说笑
    2021-02-02 11:09

    I understand you could already have bunch of threads actively polling or taking the queue but I still feel not quite right about your flow/design.

    The queue becomes empty doesn't mean the previously added tasks are finished, somes of the items could take ages to process, so it is not too useful to check for empty.

    So what you should do is forget about the BlockingQueue, you can use it as any other collections. Translate the items into a Collections of Callable and make use of the ExecutorService.invokeAll().

        Collection queue = ...
        Collection> tasks = new ArrayList>();
    
        for (Item item : queue) {
            tasks.add(new Callable() {
    
                @Override
                public Result call() throws Exception {
                    // process the item ...
    
                    return result;
                }
            });
        }
    
        // look at the results, add timeout for invokeAll if necessary
        List> results = executorService.invokeAll(tasks);
    
        // done
    

    This approach will give you full control of how long your producer could wait and proper exception handling.

提交回复
热议问题