completeOnTimeout() method of CompletableFuture in Java

This method was introduced from Java 9.

This method is used to: if after a timeout period our task is still unfinished, instead of throwing out the TimeoutException exception like the orTimeout() method, our code will return the value that we passed in this method.

The following example I want to calculate the sum of two numbers and I want it to complete in 1s, but because in the process of processing, I give sleep 3s:

The result will return the value you passed into the completeOnTimeout() method, which is 0:

completeOnTimeout() method of CompletableFuture in Java
If I now increase the timeout time to 4s:

The result would be:

completeOnTimeout() method of CompletableFuture in Java

 

Add Comment