- Home
- Skills
- APIs & Backend
- completablefuture patterns
completablefuture patterns
Implement non-blocking asynchronous pipelines in Java using CompletableFuture patterns for parallel I/O and task chaining.
Free
Works with the AI Agents you already use
completablefuture patterns
Example session with this skill installed
CompletableFuture best practices for asynchronous Java pipelines: operator
selection (supplyAsync, thenApply, thenCompose, thenCombine, allOf, anyOf),
the two-phase launch/join pattern, anti-patterns (blocking inside the
pipeline, shared mutable state), dedicated executors with named
ThreadFactory, bounding in-flight tasks with Semaphore and
Gatherers.mapConcurrent (Java 24+), error handling with exceptionally/
handle/whenComplete, timeouts with orTimeout/completeOnTimeout, and
sealed response types for modeling failure as data in fan-in reductions.
- Read your context and instructions
- Compiled the completablefuture patterns
I will implement a parallel supplier price fetcher using a non-blocking CompletableFuture pipeline. This implementation uses allOf to coordinate the requests and thenApply to process the results once all tasks complete.
Parallel Supplier Pipeline
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
public class PriceAggregator {
// Dedicated executor to avoid starving the common pool
private final ExecutorService executor = Executors.newFixedThreadPool(10);
public CompletableFuture<Double> getBestDiscountedPrice(String productId, double discountRate) {
List<String> suppliers = List.of("SupplierA", "SupplierB", "SupplierC");
// 1. Launch all requests in parallel
List<CompletableFuture<Double>> priceFutures = suppliers.stream()
.map(s -> fetchPriceAsync(s, productId))
.toList();
// 2. Create a trigger that completes when all prices are back
return CompletableFuture.allOf(priceFutures.toArray(new CompletableFuture[0]))
.thenApply(v -> {
// 3. Collect and process results (safe to join() here as all are done)
return priceFutures.stream()
.map(CompletableFuture::join)
.min(Double::compare)
.map(min -> min * (1 - discountRate))
.orElse(0.0);
})
.orTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
.exceptionally(ex -> {
System.err.println("Failed to aggregate prices: " + ex.getMessage());
return 0.0;
});
}
private CompletableFuture<Double> fetchPriceAsync(String supplier, String productId) {
return CompletableFuture.supplyAsync(() -> {
// Simulate blocking I/O call
return 100.0 + Math.random() * 50;
}, executor);
}
}
Next steps
- Define a custom
ThreadFactoryto give your executor threads meaningful names for easier debugging. - Replace the primitive
Doublewith a sealedPriceResultrecord to distinguish between valid prices and "Not Found" responses. - Implement
completeOnTimeoutif you want to return a cached price instead of throwing an exception when a supplier is slow.
Connects securely to your tools. The creator never sees your data.
About this skill
Blocking calls in Java applications throttle throughput and waste resources. This skill provides production-ready patterns for building non-blocking asynchronous pipelines using Java CompletableFuture.
What it does
- Pipeline construction Building multi-stage async chains using
thenApply,thenCompose, andthenCombine. - Parallel execution Coordinating concurrent tasks with
allOffor waiting andanyOffor race conditions. - Resource management Configuring dedicated
ExecutorServiceinstances and customThreadFactorysettings for specific workloads. - Resilient error handling Implementing timeouts with
orTimeout, fallback values viaexceptionally, and unified result processing withhandle. - Concurrency control Managing in-flight task density using
SemaphoreorGatherers.mapConcurrentto prevent resource exhaustion.
How it works
- Identify blocking bottlenecks Locating synchronous HTTP calls, database queries, or remote service requests.
- Apply composition patterns Selecting between
thenComposefor dependent tasks orthenCombinefor independent parallel work. - Configure execution environment Defining specialized thread pools to isolate I/O-bound tasks from CPU-bound logic.
- Implement recovery Adding exception handling and timeouts to ensure the pipeline fails gracefully.
Frameworks & tools
Targeted at modern Java development (Java 21+) using the standard library. Support includes ExecutorService, ForkJoinPool, and structured concurrency concepts.
Why this beats prompting it yourself
Generic AI responses often recommend blocking get() calls or overlook the ForkJoinPool.commonPool() thread starvation issues. This skill enforces non-blocking terminal operations and correct usage of the *Async variants to prevent thread leaking and deadlocks.
Use cases
- E-commerce checkout Aggregating shipping rates and inventory stock from multiple third-party APIs concurrently.
- Microservices orchestration Chaining calls where the output of one service is required for the input of another.
- Batch processing Parallelizing a large list of tasks while bounding the number of active threads.
Known limitations
Requires Java 19 or higher for AutoCloseable ExecutorService support. Specific Java 21+ features like unnamed variables or Gatherers need adaptation for older environments.
Requires Java 19+ for AutoCloseable ExecutorService. Uses Java 21 syntax (e.g., unnamed variables). Assumes basic familiarity with functional interfaces.
How to use
- 1
Connect your agent to the Agensi MCP
Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup
- 2
Sign in to Agensi
Your agent shows a sign-in link. Sign in and click Allow.
- 3
Ask for what you need
Your agent loads this skill and uses it on your task. It always asks before any payment.
Reviews
No reviews yet
Be one of the first to try it. Every listed skill goes through the trust checks below.
Security scanned
Checked by our 8-point scan before listing
Fresh listing
Recently published to Agensi
Free forever
No account required to browse
Trust & safety
Security scan
Security scan passed 12 days ago
- Free with an Agensi account
Permissions
No special permissions declared or detected