user51
user51

Reputation: 10163

correct way to handle timeout in CompletableFuture.allof and logging the timed out futures

I've ItemDetails and ItemPriceDetails defined as below -

class ItemDetails {
  private int itemId;
  private int uom;
  private int zipcode;
  private String promoCode;
}

class ItemPriceDetails {
  private int itemId;
  private int uom;
  private int zipcode;
  private float totalCost;
  private float totalTax;
  private TaxDetails taxDetails;
  private DiscountDetails discountDetails;
}

InventoryTargetExecutors is third party jar which provides fetchPrice functions which takes ItemDetails as input and returns CompletableFuture<ItemPriceDetails> as output.

I want to call multiple InventoryTargetExecutors in parallel using CompletableFuture.allof function with specified timeout and print the InventoryTargetExecutors that are timedout during the invocation.

ItemDetails  ids = ...;
List<InventoryConfigExecutors> inventoryConfigExecutors = applicationContext.get("InventoryConfigExecutors");
List<CompletableFuture<Pair<ItemPriceDetails, InventoryConfigExecutors>>> priceFutures =  inventoryConfigExecutors.stream().map(ice -> Pair.of(ice.fetchPrice(ids), ice)).collect(Collectors.toList());
CompletableFuture<Void> futuresExecuted = CompletableFuture.allOf(priceFutures.toArray(new CompletableFuture[priceFutures.size()]));

I don't know how to timeout the the priceFutures using CompletableFuture.allof and at the same time log the InventoryConfigExecutors that are timed out.

Upvotes: 3

Views: 2404

Answers (1)

kewne
kewne

Reputation: 2298

If using JDK 9 or higher, CompletableFuture.orTimeout will allow you to set the timeout. For earlier versions, you need to implement that yourself, possibly by scheduling a task that calls completeExceptionally.

For logging, you can use whenComplete and check the throwable argument, logging if it’s present. Note: this does not distinguish between timeouts or other failures.

Upvotes: 1

Related Questions