Subjects

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

How does @Async work in Spring Boot and what are its limitations? स्प्रिंग बूट में @Async कैसे काम करता है और इसकी सीमाएँ क्या हैं?

Answer

@Async, enabled with @EnableAsync, runs an annotated method on a separate thread from a configured thread pool instead of the calling thread, letting the caller continue immediately without waiting for the method to finish — useful for fire-and-forget work like sending an email or logging an audit event.

Like @Transactional and @Cacheable, it works through a Spring proxy, so it has no effect on self-invoked calls within the same class. A void-returning async method silently swallows exceptions unless an AsyncUncaughtExceptionHandler is configured; a method that needs to report success/failure back to the caller should return CompletableFuture<T> instead of void.

@Async
public CompletableFuture<Void> sendWelcomeEmail(String email) {
    emailClient.send(email, "Welcome!");
    return CompletableFuture.completedFuture(null);
}

@Async, जिसे @EnableAsync से सक्षम किया जाता है, एनोटेटेड मेथड को कॉलिंग थ्रेड के बजाय एक कॉन्फ़िगर्ड थ्रेड पूल से अलग थ्रेड पर चलाता है, जिससे कॉलर मेथड के खत्म होने की प्रतीक्षा किए बिना तुरंत आगे बढ़ सकता है।

@Transactional और @Cacheable की तरह, यह स्प्रिंग प्रॉक्सी के ज़रिए काम करता है, इसलिए उसी क्लास के अंदर सेल्फ-इनवोक्ड कॉल्स पर इसका कोई प्रभाव नहीं पड़ता। एक void रिटर्न करने वाला async मेथड चुपचाप एक्सेप्शन निगल जाता है जब तक AsyncUncaughtExceptionHandler कॉन्फ़िगर न किया जाए।

@Async
public CompletableFuture<Void> sendWelcomeEmail(String email) {
    emailClient.send(email, "Welcome!");
    return CompletableFuture.completedFuture(null);
}

Was this answer clear?