CompletableFuture - An asynchronous result plus a pipeline of callbacks: supplyAsync, thenApply, thenCompose, thenCombine, allOf, exceptionally and handle. CompletableFuture<User> user = CompletableFuture.supplyAsync(() -> userClient.get(id), ioExecutor); CompletableFuture<List<Order>> orders = CompletableFuture.supplyAsync(() -> orderClient.list(id), ioExecutor); Dashboard d = user.thenCombine(orders, Dashboard::new) .orTimeout(2, TimeUnit.SECONDS) .join(); - Good for composing independent operations and running them concurrently. - Pitfalls: - Without an explicit executor, supplyAsync uses ForkJoinPool.commonPool(), which is sized for CPU work; blocking I/O there can starve the whole application. Always pass a dedicated executor for blocking calls. - cancel(true) on a CompletableFuture does not interrupt the running task; it only completes the future exceptionally. The underlying work keeps running unless it checks a cancellation flag itself. - Exceptions are wrapped in CompletionException and can be silently lost if no stage handles them. - Callback chains are harder to read and debug (stack traces span threads). Virtual threads (Java 21+) - Lightweight threads managed by the JVM. Millions can exist; when a virtual thread blocks on I/O, the JVM unmounts it from its carrier (platform) thread, which is freed for other work. - You write simple blocking code, one thread per task: Executors.newVirtualThreadPerTaskExecutor(), Thread.ofVirtual().start(...). Spring Boot 3.2+ can enable them with spring.threads.virtual.enabled=true. - Excellent for I/O-bound servers: high concurrency without reactive or callback-style code. Risks with virtual threads - Pinning: in Java 21, blocking inside a synchronized block or a native call pins the virtual thread to its carrier, reducing scalability. JDK 24 removed pinning for synchronized (JEP 491); on older versions prefer ReentrantLock for blocking critical sections. - Do not pool virtual threads; create one per task. Limit concurrency to downstream resources with semaphores, because "unlimited threads" can overwhelm databases or APIs (connection pools still cap actual concurrency). - ThreadLocal-heavy code can use a lot of memory with millions of threads; scoped values are the modern alternative. - CPU-bound work gains nothing: virtual threads help waiting, not computing. Cancellation with virtual threads - Interruption works normally: future.cancel(true) or thread.interrupt() interrupts blocking I/O and sleeps that respond to interrupts. - Structured concurrency (StructuredTaskScope, a preview API in recent JDKs) groups subtasks so failure or cancellation of one cancels the rest and nothing leaks. Choosing: virtual threads for straightforward blocking I/O code at high concurrency; CompletableFuture when you need explicit composition of async results; reactive frameworks (WebFlux) when you need backpressure and streaming.
Ravindra Wadile · · 0 likes