When should I use a CompletionService over an ExecutorService?

后端 未结 10 2144
后悔当初
后悔当初 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:36

    there is another advantage of using completionservice: Performance

    when you call future.get(), you are spin waiting:

    from java.util.concurrent.CompletableFuture

      private Object waitingGet(boolean interruptible) {
            Signaller q = null;
            boolean queued = false;
            int spins = -1;
            Object r;
            while ((r = result) == null) {
                if (spins < 0)
                    spins = (Runtime.getRuntime().availableProcessors() > 1) ?
                        1 << 8 : 0; // Use brief spin-wait on multiprocessors
                else if (spins > 0) {
                    if (ThreadLocalRandom.nextSecondarySeed() >= 0)
                        --spins;
                }
    

    when you have a long-running task, this will be a disaster for performance.

    with completionservice, once the task is done, it's result will be enqueued and you can poll the queue with lower performance overhand.

    completionservice achieve this by using wrap task with a done hook.

    java.util.concurrent.ExecutorCompletionService

        private class QueueingFuture extends FutureTask {
        QueueingFuture(RunnableFuture task) {
            super(task, null);
            this.task = task;
        }
        protected void done() { completionQueue.add(task); }
        private final Future task;
    }
    

提交回复
热议问题