根据甲骨文,staticCompletableFuturesupplyAsync(Suppliersupplier)ReturnsanewCompletableFuturethatisasynchronouslycompletedbyataskrunningintheForkJoinPool.commonPool()withthevalueobtainedbycallingthegivenSupplier.staticCompletableFuturesupplyAsync(Suppliersupplier,Executorexecutor)ReturnsanewCompletable
我刚刚开始探索Java8的一些并发特性。让我有点困惑的一件事是这两个静态方法:CompletableFuturerunAsync(Runnablerunnable)CompletableFuturesupplyAsync(Suppliersupplier)有谁知道他们为什么选择使用接口(interface)供应商?使用Callable是不是更自然,类比Runnable返回值?那是因为供应商没有抛出无法处理的异常吗? 最佳答案 简答不,使用Callable不是更自然而不是Supplier在CompletableFuture.suppl
我刚刚开始探索Java8的一些并发特性。让我有点困惑的一件事是这两个静态方法:CompletableFuturerunAsync(Runnablerunnable)CompletableFuturesupplyAsync(Suppliersupplier)有谁知道他们为什么选择使用接口(interface)供应商?使用Callable是不是更自然,类比Runnable返回值?那是因为供应商没有抛出无法处理的异常吗? 最佳答案 简答不,使用Callable不是更自然而不是Supplier在CompletableFuture.suppl
假设我有一些异步计算,例如:CompletableFuture.supplyAsync(()->createFoo()).thenAccept(foo->doStuffWithFoo(foo));如果异步供应商根据某些指定的超时超时,是否有一种很好的方法可以为foo提供默认值?理想情况下,此类功能也会尝试取消运行缓慢的供应商。例如,是否有类似于以下假设代码的标准库功能:CompletableFuture.supplyAsync(()->createFoo()).acceptEither(CompletableFuture.completedAfter(50,TimeUnit.MILLI
假设我有一些异步计算,例如:CompletableFuture.supplyAsync(()->createFoo()).thenAccept(foo->doStuffWithFoo(foo));如果异步供应商根据某些指定的超时超时,是否有一种很好的方法可以为foo提供默认值?理想情况下,此类功能也会尝试取消运行缓慢的供应商。例如,是否有类似于以下假设代码的标准库功能:CompletableFuture.supplyAsync(()->createFoo()).acceptEither(CompletableFuture.completedAfter(50,TimeUnit.MILLI
要并行或异步运行一些东西,我可以使用ExecutorService:Futuresubmit(Runnabletask,Tresult);或CompletableFutureAPI:staticCompletableFuturesupplyAsync(Suppliersupplier,Executorexecutor);(假设我在这两种情况下都使用同一个Executor)除了返回类型Future与CompletableFuture有什么显着差异。或者什么时候用什么?如果我使用CompletableFuture有什么区别?默认APIExecutor(没有执行者的方法)?
要并行或异步运行一些东西,我可以使用ExecutorService:Futuresubmit(Runnabletask,Tresult);或CompletableFutureAPI:staticCompletableFuturesupplyAsync(Suppliersupplier,Executorexecutor);(假设我在这两种情况下都使用同一个Executor)除了返回类型Future与CompletableFuture有什么显着差异。或者什么时候用什么?如果我使用CompletableFuture有什么区别?默认APIExecutor(没有执行者的方法)?
CompletableFuture::supplyAsync(()->IO绑定(bind)查询)我如何为CompletableFuture::supplyAsync选择执行器以避免污染ForkJoinPool.commonPool()。Executors中有很多选项(newCachedThreadPool、newWorkStealingPool、newFixedThreadPool等)我读到了新的ForkJoinPoolhere如何为我的用例选择合适的? 最佳答案 你应该使用publicstaticCompletableFuture
CompletableFuture.supplyAsync(()->{transporter.write(req);//heretakethevaluefromablockingqueue,willthrowainterruptedExceptionreturnresponseQueue.take();},executorService);常见的处理interruptedException的方法要么是再次中断要么直接抛出interruptedException,但是两者都行不通。有人知道吗? 最佳答案 我这样修改代码。Complet