|
|
Java 8 CompletableFuture - Running Tasks in Parallel
Author: Venkata Sudhakar
CompletableFuture lets you run tasks asynchronously and combine their results. The most practical use case is running multiple independent operations in parallel - for example, fetching data from three different services at the same time instead of one after the other. CompletableFuture.allOf() waits for all tasks to finish, so you can start them all simultaneously and collect the results once every task is done. Without CompletableFuture, three sequential calls each taking 1 second would take 3 seconds total. With allOf(), all three run at the same time and the total time is just the duration of the slowest one - about 1 second. This is a simple but powerful win for any code that makes multiple independent calls. The below example shows the difference between sequential and parallel execution, then shows how to collect all results into a list.
It gives the following output (all three complete in ~1 second, not 3 seconds),
customers: 125000 rows
orders: 125000 rows
products: 125000 rows
// Sequential would take ~3 seconds
// Parallel takes ~1 second (limited by the slowest task)
Use supplyAsync() when your task returns a value. Use runAsync() when your task returns nothing. Both use the common ForkJoinPool by default, or you can pass your own Executor as a second argument to control the thread pool size.
|
|