[英]How do i mock completable Future's supplyAsync methods response?
[英]Passing Class that runs task to Completable Future SupplyAsync
嘗試比較期貨與已完成期貨的實施,並檢查可完成期貨的非阻塞性質是否是解決我的問題的更好用例。 讓我的可完成實現正常工作時遇到問題。
Collection<Future<ArrayList<MeterTariffValues>>> futures = new ArrayList<>();
List<CompletableFuture<GetSiteMeterTariffValues>> completableFutures = new ArrayList<>();
for (Site site : sites) {
completableFutures.add(
CompletableFuture.supplyAsync(new Supplier<GetSiteMeterTariffValues>() {
@Override
public GetSiteMeterTariffValues get() {
return new GetSiteMeterTariffValues(
site.getSite_id(),
methaneConversionVal,
nitrogenConversionVal,
bu_id,
region_id,
facility_id,
status,
resource_id,
metertype_id,
currentCalendarYear,
currentFiscalYear,
fiscalYearStartMonth,
dates,
meterMapper,
sqlSessionTemplate);
}
}, taskExecutor)
);
futures.add(
taskExecutor.submit(
new GetSiteMeterTariffValues(
site.getSite_id(),
methaneConversionVal,
nitrogenConversionVal,
bu_id,
region_id,
facility_id,
status,
resource_id,
metertype_id,
currentCalendarYear,
currentFiscalYear,
fiscalYearStartMonth,
dates,
meterMapper,
sqlSessionTemplate)));
}
Completable 實現的問題在於,它無法識別 GetSiteMeterTariffValues 在任務完成后返回不同的類型。
它返回
public ArrayList<MeterTariffValues> call()
但是任務執行者對此很好
for (Future<ArrayList<MeterTariffValues>> future : futures) {
long start = System.currentTimeMillis();
ArrayList<MeterTariffValues> siteMeterTariffMonthlyValues = future.get();
long end = System.currentTimeMillis();
long totalMS = end - start;
total += totalMS;
meterTariffValues.addAll(siteMeterTariffMonthlyValues);
}
所以我想知道我如何用 completablefutures 做類似的事情。
注意:GetSiteMeterTariffValues 實現了 Callable<ArrayList>
CompletableFuture.supplyAsync()
期望Supplier
相當於Callable
for ExecutorService
。
您目前的做法是,您只是提供一個創建Callable
的Supplier
,但當然不會調用您的Callable
( GetSiteMeterTariffValues
)。
您只需要讓GetSiteMeterTariffValues
實現Supplier
並直接在CompletableFuture.supplyAsync()
中使用它:
CompletableFuture.supplyAsync(
new GetSiteMeterTariffValues(
site.getSite_id(),
methaneConversionVal,
nitrogenConversionVal,
bu_id,
region_id,
facility_id,
status,
resource_id,
metertype_id,
currentCalendarYear,
currentFiscalYear,
fiscalYearStartMonth,
dates,
meterMapper,
sqlSessionTemplate),
taskExecutor)
請注意, Supplier
不允許拋出已檢查的異常,因此您不能只使用對Callable.call()
的方法引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.