AI Briefing
KO

Asynchronous Processing with Java CompletableFuture

·2024.01.04 00:00

Key point

CompletableFuture turns sequential execution into asynchronous processing to improve performance and stability.

Details

While separating a centralized database by domain, running the pre- and post-migration logic sequentially doubled the total execution time, and a 1-second discrepancy caused query results to differ, making even normal cases fail comparison.

To solve this problem, Java 8's CompletableFuture was used to apply asynchronous processing. The key point is that it complements the inconveniences of operation chaining and exception handling that the existing Future had, while allowing asynchronous flows to be handled more flexibly.

A CompletableFuture instance is created with supplyAsync(), and completion can be awaited with get() or join(). Subsequent operations are handled by combining the following methods depending on the purpose.

  • thenApply(): Used when you need to receive the result of the previous stage and compute the next value.
  • thenAccept(): Used when you only need to consume the result without needing a return value.
  • thenRun(): Used when you only need to perform a follow-up action without a return value.

When chaining operations, it's important to distinguish between thenCompose() and thenCombine(). thenCompose() attaches another asynchronous task based on the result of the previous stage, while thenCombine() combines the results of two independent Futures.

For post-processing that doesn't need a result, thenAcceptBoth() is useful, and when you need to wait for multiple tasks simultaneously, allOf() can be used to bundle parallel execution. However, since allOf() returns Void by default, additional handling such as join() is needed to retrieve the results again.

Finally, this article also covers exception handling and Timeout, summarizing practical patterns for improving performance degradation and result inconsistency caused by sequential processing through asynchronous processing.

This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.

Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.