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 public class RefreshTokenSuccessHandler implements AuthenticationSuccessHandler { private final RefreshTokenService refreshTokenService;
Issuing JWT and refresh tokens on login in Spring
authentication
jwt
http-cookies
Intermediate
7 steps
java
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule;
Serializing Money to JSON in Spring
serialization
jackson
money
Intermediate
8 steps
javascript
import { unstable_cache, revalidateTag } from 'next/cache' import { db } from '@/lib/db' export const getDashboardStats = unstable_cache(
Caching dashboard stats in Next.js
caching
cache-invalidation
tag-based-revalidation
Intermediate
8 steps
java
@Component @Order(Ordered.HIGHEST_PRECEDENCE) public class TenantResolutionFilter extends OncePerRequestFilter {
How a tenant-resolution filter works in Spring
multi-tenancy
servlet-filter
thread-local
Intermediate
8 steps
java
@Repository public interface SubscriptionRepository extends JpaRepository<Subscription, Long> { @Modifying(clearAutomatically = true, flushAutomatically = true)
Bulk JPQL updates in a Spring Data repository
jpql
bulk-update
modifying-query
Intermediate
5 steps
java
package com.example.uploads.config; import jakarta.servlet.MultipartConfigElement; import org.springframework.boot.web.servlet.MultipartConfigFactory;
Configuring upload size limits in Spring
file-upload
exception-handling
http-errors
Intermediate
6 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.