I have a couple of completableFutures, with completeOnTimeout ( and return empty object in this case), for example:
return CompletableFuture.supplyAsync(() -> {
try {
log.info("#####Start sleeping");
Thread.sleep(9000);
log.info("#####Finished sleeping");
} catch (InterruptedException e){
log.info("#####Interrupted");
}
TestEntity reputationEntity = getTestEntity(destination);
return getTestDTO(destination, accountId, testEntity);}).completeOnTimeout(new testDTO(), asyncTimeoutMls, TimeUnit.MILLISECONDS);
How do I add log the case of completeOnTimeout?
Later in the code, I combine this c future with another one, by:
CompletableFuture.allOf(test1ComletableFuture, test2ComletableFuture).join();
So I would like to know ( and log) when one of this feature completed on timeout.
Something like lambda expression inside of completeOnTimeout?
According to completeOnTimeout
implementation, there is no option to specify any code or logging, however it turns out completeOnTimeout
under the hood just schedules a .complete()
call via a ScheduledThreadPoolExecutor
. So for me it seems absolutely ok to implement it by yourself. A brief example:
private final ScheduledThreadPoolExecutor futureCompleteExecutor = new ScheduledThreadPoolExecutor(1);
and then
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "executed");
futureCompleteExecutor.schedule(() -> {
if (completableFuture.complete("timeouted")) {
// log
}
}, 1, TimeUnit.MINUTES)
Extract a method to make usage smoothly. Don't execute blocking or long-running code in a scheduled task. Not a perfect, yet flexible approach.