ExecutorService cpuBound = Executors.newFixedThreadPool(4);
or
ExecutorService ioBound = Executors.newCachedThreadPool(200);
CompletableFuture.supplyAsync(() -> getOrder(), ioBound)
.thenApplyAsync(order -> enrich(order), cpuBound)
.thenApplyAsync(order -> getOrder(order))
.exectionally(e -> new Fail())
.thenAccept(order -> sendEmail(order));
thenApplyAsync 和 thenApply区别是。 thenApply是保持在同一个线程。thenApplyAsync是可以用另一个线程来执行。
第三行exectionally 可以catch any exception send out from getOrder/enrich/ getOrder
第四行如果没有指定线程池,则用默认ForkJoinPool.commonPool() 来进行。
- FixedThreadPool
- CachedThreadPool
- ScheduledThreadPool
- SinglethreadedExecutor
submit tasks: