CompletableFuture thenCombine返回类型推断问题及解决咨询
问题原因
你当前的代码中,thenCombine的函数参数返回的是CompletableFuture<List<InvestmentsResponse>>,因此thenCombine的最终结果是CompletableFuture<CompletableFuture<List<InvestmentsResponse>>>,这和你期望的CompletableFuture<List<InvestmentsResponse>>类型不匹配,导致编译器报错。
正确解决方案
方案一:扁平化嵌套的CompletableFuture
使用thenCombine后链式调用thenCompose,将嵌套的CompletableFuture扁平化:
CompletableFuture<List<InvestmentsResponse>> investmentResponsesFuture = money.thenCombine(contracts, (moneyResponse, contractsResponse) -> getInvestments(moneyResponse, contractsResponse, omniPlanNumber) ).thenCompose(Function.identity());
thenCompose会接收一个返回CompletableFuture的函数,这里Function.identity()直接返回内层的CompletableFuture<List<InvestmentsResponse>>,从而将外层的CompletableFuture<CompletableFuture<...>>转换为你需要的CompletableFuture<List<...>>,全程保持异步,不会阻塞线程。
方案二:先等待两个Future完成再执行后续逻辑
使用CompletableFuture.allOf先等待contracts和money两个Future完成,再调用getInvestments:
CompletableFuture<List<InvestmentsResponse>> investmentResponsesFuture = CompletableFuture.allOf(contracts, money) .thenCompose(v -> getInvestments(money.join(), contracts.join(), omniPlanNumber));
这里allOf会异步等待两个Future都完成,之后调用join()是完全安全的——因为此时两个Future已经处于完成状态,join()会立即返回结果,不会造成线程阻塞,同样符合异步规范。
注意事项
不要修改getInvestments让它直接返回List(调用join()),这种做法会阻塞当前线程,破坏CompletableFuture的异步执行流程,违背其设计初衷。
内容的提问来源于stack exchange,提问作者Avishek Mazumder

