java 41 lines · 8 steps

Enforcing HTTP timeouts with a Future

A thread pool runs each fetch off-thread so the caller can bound it with Future.get and cancel on timeout.

Explained by highlit
1public class TimedFetchService {
2 
3 private final ExecutorService executor = Executors.newFixedThreadPool(8);
4 private final HttpClient httpClient = HttpClient.newHttpClient();
5 
6 public String fetchWithTimeout(URI uri, Duration timeout) {
7 Future<String> future = executor.submit(() -> {
8 HttpRequest request = HttpRequest.newBuilder(uri).GET().build();
9 HttpResponse<String> response =
10 httpClient.send(request, HttpResponse.BodyHandlers.ofString());
11 return response.body();
12 });
13 
14 try {
15 return future.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
16 } catch (TimeoutException e) {
17 future.cancel(true);
18 throw new FetchTimeoutException(
19 "Request to " + uri + " exceeded " + timeout.toMillis() + "ms", e);
20 } catch (ExecutionException e) {
21 throw new FetchFailedException("Request to " + uri + " failed", e.getCause());
22 } catch (InterruptedException e) {
23 future.cancel(true);
24 Thread.currentThread().interrupt();
25 throw new FetchFailedException("Interrupted while fetching " + uri, e);
26 }
27 }
28 
29 @PreDestroy
30 public void shutdown() {
31 executor.shutdown();
32 try {
33 if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
34 executor.shutdownNow();
35 }
36 } catch (InterruptedException e) {
37 executor.shutdownNow();
38 Thread.currentThread().interrupt();
39 }
40 }
41}
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1Wrapping blocking work in a Future lets you impose a wall-clock deadline the underlying call may not support.
  2. 2Each checked exception from Future.get maps to a distinct failure mode that deserves its own handling.
  3. 3A pooled executor needs an explicit lifecycle so its threads shut down cleanly with the owning component.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Enforcing HTTP timeouts with a Future — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code