Waiting Early Termination for a List of Futures
When dealing with asynchronous tasks represented by futures, it's often crucial to wait until all processing is complete or an error occurs. However, waiting unnecessarily for all tasks to complete even after an error has occurred is undesirable.
To address this issue, consider the following steps:
Utilize a CompletionService:
Monitor Futures Sequentially:
Cancel Remaining Tasks:
Here's an example that demonstrates this approach:
<code class="java">Executor executor = Executors.newFixedThreadPool(4); CompletionService<SomeResult> completionService = new ExecutorCompletionService<SomeResult>(executor); // 4 tasks for(int i = 0; i < 4; i++) { completionService.submit(new Callable<SomeResult>() { public SomeResult call() { // Processing code return result; } }); } int received = 0; boolean errors = false; while(received < 4 && !errors) { Future<SomeResult> resultFuture = completionService.take(); // Blocks until available try { SomeResult result = resultFuture.get(); received ++; // Process the result } catch(Exception e) { // Log or handle the error errors = true; } if (errors) { // Cancel any remaining tasks executor.shutdown(); break; } }</code>
The above is the detailed content of How Can I Efficiently Handle Errors and Early Termination When Working with Futures?. For more information, please follow other related articles on the PHP Chinese website!