Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 8 of 10 · Caching, Async & Scheduling
Interview question

What is the difference between CompletableFuture and @Async, and how are they used together? CompletableFuture और @Async में क्या अंतर है, और इन्हें एक साथ कैसे उपयोग किया जाता है?

Answer

CompletableFuture is a general-purpose Java class (not Spring-specific) representing a value that will be available in the future, with rich composition methods like thenApply(), thenCombine(), and allOf() for chaining and combining async operations. @Async is Spring's mechanism for actually running a method on a separate thread pool in the first place.

They're commonly combined: an @Async-annotated method returns a CompletableFuture<T>, giving the caller a handle to track completion, retrieve the result with get() or join(), and compose it with other async calls — for example, fetching data from two independent services concurrently and combining the results once both complete.

@Async
public CompletableFuture<Price> getPrice(String productId) {
    return CompletableFuture.completedFuture(pricingClient.getPrice(productId));
}

CompletableFuture<Price> priceFuture = pricingService.getPrice("p1");
CompletableFuture<Stock> stockFuture = inventoryService.getStock("p1");
CompletableFuture.allOf(priceFuture, stockFuture).join();

CompletableFuture एक सामान्य-उद्देश्य वाला Java क्लास है (स्प्रिंग-विशिष्ट नहीं) जो भविष्य में उपलब्ध होने वाले वैल्यू को दर्शाता है, जिसमें thenApply(), thenCombine(), allOf() जैसी समृद्ध कंपोज़िशन मेथड्स होती हैं। @Async स्प्रिंग का तंत्र है जो पहली बार किसी मेथड को अलग थ्रेड पूल पर चलाता है।

इन्हें आमतौर पर एक साथ मिलाया जाता है: एक @Async-एनोटेटेड मेथड CompletableFuture<T> रिटर्न करता है, जिससे कॉलर को पूर्णता ट्रैक करने और get() या join() से परिणाम प्राप्त करने का हैंडल मिलता है।

@Async
public CompletableFuture<Price> getPrice(String productId) {
    return CompletableFuture.completedFuture(pricingClient.getPrice(productId));
}

Was this answer clear?