CompletableFuture orTimeout And completeOnTimeout
Bound slow async calls with orTimeout and completeOnTimeout so a hung supplier resolves to a fallback value instead of blocking the caller forever.
Code
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class DeadlineFetch {
public static void main(String[] args) throws Exception {
// 1) 永不完成的 future:50ms 后被 orTimeout 以 TimeoutException 异常完成
CompletableFuture<String> stuck = new CompletableFuture<>();
try {
stuck.orTimeout(50, TimeUnit.MILLISECONDS).get(1, TimeUnit.SECONDS);
} catch (ExecutionException e) {
System.out.println("orTimeout cause: " + e.getCause().getClass().getSimpleName());
}
// 2) 同样场景改用 completeOnTimeout:超时后用兜底值正常完成
String value = new CompletableFuture<String>()
.completeOnTimeout("cached-report", 50, TimeUnit.MILLISECONDS)
.get(1, TimeUnit.SECONDS);
System.out.println("completeOnTimeout value: " + value);
// 3) 或在异常完成后由 exceptionally 给出降级结果
String fallback = new CompletableFuture<String>()
.orTimeout(50, TimeUnit.MILLISECONDS)
.exceptionally(ex -> "degraded: " + ex.getClass().getSimpleName())
.get(1, TimeUnit.SECONDS);
System.out.println("fallback value: " + fallback);
}
}How it works
CompletableFuture orTimeout And completeOnTimeout is built around the class DeadlineFetch.
Using it
Running the file prints labeled results such as orTimeout cause:, completeOnTimeout value:, fallback value: — each operation’s effect is visible in the output.
Key statements
CompletableFuture<String> stuck = new CompletableFuture<>();
String fallback = new CompletableFuture<String>()
.orTimeout(50, TimeUnit.MILLISECONDS)
.exceptionally(ex -> "degraded: " + ex.getClass().getSimpleName())
.get(1, TimeUnit.SECONDS);
String value = new CompletableFuture<String>()
.completeOnTimeout("cached-report", 50, TimeUnit.MILLISECONDS)
.get(1, TimeUnit.SECONDS);
Interactive Tools for This Topic
FAQ
- What does CompletableFuture orTimeout And completeOnTimeout print when run?
- The script runs standalone; its 3 labeled outputs include `orTimeout cause:`, `completeOnTimeout value:`, `fallback value:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.