completablefuture patterns

    1

    Implement non-blocking asynchronous pipelines in Java using CompletableFuture patterns for parallel I/O and task chaining.

    Free

    Security scanned

    Works with the AI Agents you already use

    Claude CodeClaude CodeCursorCursorCodex CLICodex CLIMuseMuseDotsDots+21 more

    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 ThreadFactory to give your executor threads meaningful names for easier debugging.
    • Replace the primitive Double with a sealed PriceResult record to distinguish between valid prices and "Not Found" responses.
    • Implement completeOnTimeout if 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, and thenCombine.
    • Parallel execution Coordinating concurrent tasks with allOf for waiting and anyOf for race conditions.
    • Resource management Configuring dedicated ExecutorService instances and custom ThreadFactory settings for specific workloads.
    • Resilient error handling Implementing timeouts with orTimeout, fallback values via exceptionally, and unified result processing with handle.
    • Concurrency control Managing in-flight task density using Semaphore or Gatherers.mapConcurrent to prevent resource exhaustion.

    How it works

    1. Identify blocking bottlenecks Locating synchronous HTTP calls, database queries, or remote service requests.
    2. Apply composition patterns Selecting between thenCompose for dependent tasks or thenCombine for independent parallel work.
    3. Configure execution environment Defining specialized thread pools to isolate I/O-bound tasks from CPU-bound logic.
    4. 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. 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. 2

      Sign in to Agensi

      Your agent shows a sign-in link. Sign in and click Allow.

    3. 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

    Listed12 days ago

    What's inside

    Frequently Asked Questions

    This skill provides production-grade templates for Java CompletableFuture that prioritize non-blocking operations, helping you avoid common pitfalls like thread starvation in the commonPool or accidental blocking calls to .get().

    The skill is optimized for Java 21+, leveraging features like structured concurrency concepts and modern ExecutorService management, though the core patterns can be adapted for Java 11+ environments.

    You receive a comprehensive set of implementation patterns including pipeline construction, specialized error handling strategies, and configuration templates for dedicated I/O thread pools.

    Yes, the skill includes patterns specifically for microservice orchestration, demonstrating how to use thenCompose and thenCombine to chain or aggregate multiple external API calls efficiently.

    The skill provides explicit guidance on using Semaphores and custom ExecutorService configurations to bound in-flight tasks, preventing your application from crashing due to resource exhaustion during high load.

    New in APIs & Backend