ExecutorService.submit(Task) vs CompletableFuture.supplyAsync(Task, Executor)

后端 未结 3 1176
盖世英雄少女心
盖世英雄少女心 2021-01-30 16:39

To run some stuff in parallel or asynchronously I can use either an ExecutorService: Future submit(Runnable task, T result); or the CompletableFu

3条回答
  •  遥遥无期
    2021-01-30 17:18

    Besides the return type Future vs. CompletableFuture are there any remarkable differences. Or When to use what?

    It's rather simple really. You use the Future when you want the executing thread to wait for async computation response. An example of this is with a parallel merge/sort. Sort left asynchronously, sort right synchronously, wait on left to complete (future.get()), merge results.

    You use a CompleteableFuture when you want some action executed, with the result after completion, asynchronously from the executed thread. For instance: I want to do some computation asynchronously and when I compute, write the results to some system. The requesting thread may not need to wait on a result then.

    You can mimic the above example in a single Future executable, but the CompletableFuture offers a more fluent interface with better error handling.

    It really depends on what you want to do.

    And what are the differences if i use the CompletableFutureApi with default Executor (the method without executor)?

    It will delegate to ForkJoin.commonPool() which is a default size to the number of CPUs on your system. If you are doing something IO intensive (reading and writing to the file system) you should define the thread pool differently.

    If it's CPU intensive, using the commonPool makes most sense.

提交回复
热议问题