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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping blocking work in a Future lets you impose a wall-clock deadline the underlying call may not support.
- 2Each checked exception from Future.get maps to a distinct failure mode that deserves its own handling.
- 3A pooled executor needs an explicit lifecycle so its threads shut down cleanly with the owning component.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/enforcing-http-timeouts-with-a-future-explained-java-f786/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.