简体   繁体   中英

Difference between a ExecutorCompletionService and a FixedThreadPool executor

As far as I know, executor completion service provides the output from the future object regardless of the order in which the task was requested in the inbound queue, ie whichever task is completed first the Result is put into the Outbound Queue. On the other hand, FixedThreadPool also executes the tasks parallelly, then what is the difference between the two? ( Not sure whether the FixedThreadPool gives the output sequentially in the order the tasks were fed to the inbound queue )

Thanks.

FixedThreadPool is one of the variations of Executor . It uses class ThreadPoolExecutor with same values for corePoolSize and maximumPoolSize . It means, if you create FixedThreadPool with 10 threads, it will always keep exact 10 threads. If any of these threads are terminated by running task - thread pool will create new ones to keep required amount.

CompletionService arranges that submitted tasks are, upon completion, placed on a queue.

It means, that all results of submitted tasks will be in a queue and you can process them later. When you submit a task to a CompletionService , it creates a wrapper, so the result of async task is saved to queue. It doesn't create parallelism itself, instead CompletionService uses inside Executor for making parallel threads. You can pass FixedThreadPool inside, for example.

All tasks, submitted to FixedThreadPool and CompletionService will be done in parallel, without keeping the order.

CompletionService can be used, when you need to know when all of your tasks are finished. Example:

//Task extends Callable<Result>
List<Task> tasks = new ArrayList<Task>();
CompletionService<Result> cs = new ExecutorCompletionService<Result>(Executors.newFixedThreadPool(10));
tasks.forEach(task -> cs.submit(task));
for (int i = 0; i < tasks.size(); i++) { // you should know exact amount of submitted tasks
    Result r = cs.take().get();
    //process r
}

FixedThreadPool can be used in any other case, when you want to parallel threads without waiting for the results.

Also, note the difference between FixedThreadPool and CachedThreadPool . The first one is usually used when you need to keep threads alive and limit their amount. The seconds one is limited by system, it will process as many threads in parallel as possible. If a thread is in idle state in CachedThreadPool it will be automatically deleted after timeout (default is 60 seconds).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM