When should I use a CompletionService over an ExecutorService?

后端 未结 10 2145
后悔当初
后悔当初 2020-11-28 01:52

I just found CompletionService in this blog post. However, this does\'t really showcases the advantages of CompletionService over a standard ExecutorService. The same code c

10条回答
  •  鱼传尺愫
    2020-11-28 02:34

    First of all, if we do not want to waste processor time, we will not use

    while (!future.isDone()) {
            // Do some work...
    }
    

    We must use

    service.shutdown();
    service.awaitTermination(14, TimeUnit.DAYS);
    

    The bad thing about this code is that it will shut down ExecutorService. If we want to continue work with it (i.e. we have some recursicve task creation), we have two alternatives: invokeAll or ExecutorService.

    invokeAll will wait untill all tasks will be complete. ExecutorService grants us ability to take or poll results one by one.

    And, finily, recursive example:

    ExecutorService executorService = Executors.newFixedThreadPool(THREAD_NUMBER);
    ExecutorCompletionService completionService = new ExecutorCompletionService(executorService);
    
    while (Tasks.size() > 0) {
        for (final Task task : Tasks) {
            completionService.submit(new Callable() {   
                @Override
                public String call() throws Exception {
                    return DoTask(task);
                }
            });
        } 
    
        try {                   
            int taskNum = Tasks.size();
            Tasks.clear();
            for (int i = 0; i < taskNum; ++i) {
                Result result = completionService.take().get();
                if (result != null)
                    Tasks.add(result.toTask());
            }           
        } catch (InterruptedException e) {
        //  error :(
        } catch (ExecutionException e) {
        //  error :(
        }
    }
    

提交回复
热议问题