Asynchronous Timeout Implementation for CompletableFuture in JDK 8
This article proposes an asynchronous timeout implementation for CompletableFuture in JDK 8, addressing the lack of built-in timeout interruption capabilities and providing a solution for precise task timeout control.
This article addresses the limitation of CompletableFuture in JDK 8, which lacks built-in timeout interruption capabilities. The author proposes an asynchronous timeout implementation solution to solve this problem.
The article begins by explaining the common use case of CompletableFuture for parallel execution of multiple RPC calls. It demonstrates how to use CompletableFuture to execute two tasks in parallel, reducing the total execution time from 4 seconds to 2 seconds.
However, the article identifies a problem when introducing real-world scenarios where tasks have unpredictable execution times. If one task takes significantly longer than expected, it can cause the entire operation to fail. The author explains that existing solutions rely on the task's own timeout implementation, which may not be precise enough.
The article then analyzes the existing approach using JSF timeout as an example, showing how it can fail when tasks complete just before the timeout edge, causing the actual execution time to exceed the intended timeout.
For JDK 9 and above, the article mentions that CompletableFuture provides built-in orTimeout and completeTimeout methods for accurate asynchronous timeout control. It explains the implementation principle using a scheduled task that throws an exception after the specified timeout.
For JDK 8 users, the article provides a custom utility class implementation that mimics the JDK 9 functionality. The utility class includes Timeout, Canceller, and Delayer inner classes to handle the timeout logic. The implementation uses a scheduled thread pool executor to trigger the timeout task and cancel it if the original task completes first.
The article concludes by emphasizing that this solution provides a way to achieve asynchronous timeout control in JDK 8 scenarios where existing timeout mechanisms may fail or lack precision.
JD Tech Talk
Official JD Tech public account delivering best practices and technology innovation.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.