Java का CompletableFuture
In this page:
CompletableFuture<Type> future = CompletableFuture.supplyAsync(() -> value)
.thenApply(result -> transformed)
.thenAccept(result -> action);
What is CompletableFuture?
CompletableFuture, जो Java 8 में introduced हुआ, asynchronous, non-blocking programming को support करता है किसी background thread पर tasks चलाकर और आपको callbacks जोड़ने देकर जो result तैयार होने पर fire होते हैं, बजाय calling thread को इसके इंतज़ार के लिए block करने के।
उदाहरण: What is CompletableFuture?
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "done"); // runs in background
future.thenAccept(result -> System.out.println("Callback fired: " + result));
future.get(); // wait so main() doesn't exit before the callback runs
}
}
Login to try C/C++/Java/PHP code in the editor
Running Tasks with runAsync()
static runAsync() method किसी background thread pool पर asynchronously एक task execute करता है। यह एक Runnable accept करता है और कोई result return नहीं करता, जो इसे logging या notification भेजने जैसे fire-and-forget side effects के लिए सही choice बनाता है।
उदाहरण: Running Tasks with runAsync()
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> System.out.println("Fire-and-forget task")); // no result
future.get();
}
}
Login to try C/C++/Java/PHP code in the editor
SupplyAsync and Callbacks
supplyAsync() एक task चलाता है जो asynchronously एक result produce करता है, और इसके output को thenAccept() से chain करना आपको उस completed value को process करने देता है जब वह तैयार हो, chain में कहीं भी calling thread को block किए बिना।
उदाहरण: SupplyAsync and Callbacks
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture.supplyAsync(() -> 10 * 5)
.thenAccept(result -> System.out.println("Result: " + result))
.get(); // never blocks until this final wait
}
}
Login to try C/C++/Java/PHP code in the editor
Combining Futures
thenCombine() आपको दो स्वतंत्र CompletableFutures को combine करने और उनके दोनों results को साथ process करने देता है जैसे ही वे दोनों खत्म हो जाएं, जो तब उपयोगी है जब दो असंबंधित async operations (जैसे दो अलग API calls) दोनों के पूरा होने के बाद ही आप आगे बढ़ सकें।
उदाहरण: Combining Futures
// Import java.util.concurrent.CompletableFuture so it can be used by its short name
import java.util.concurrent.CompletableFuture;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) throws Exception {
// Start an asynchronous task with CompletableFuture
CompletableFuture<Integer> a = CompletableFuture.supplyAsync(() -> 5);
// Start an asynchronous task with CompletableFuture
CompletableFuture<Integer> b = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> combined = a.thenCombine(b, (x, y) -> x + y);
// Print a line to the console
System.out.println(combined.get());
}
}
Login to try C/C++/Java/PHP code in the editor
Exception Handling
exceptionally() आपको async background tasks की किसी chain के अंदर कहीं भी फेंकी गई errors को पकड़ने और handle करने देता है, एक सुरक्षित fallback value देने देते हुए बजाय exception के uncaught propagate होकर पूरे async pipeline को चुपचाप fail करने के।
उदाहरण: Exception Handling
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("task failed");
}).exceptionally(ex -> -1); // safe fallback instead of propagating uncaught
System.out.println(future.get());
}
}
Login to try C/C++/Java/PHP code in the editor
supplyAsyncके ठीक बादget()याjoin()call करना, जो thread को block करता है और asynchronous होने का फायदा हटा देता है।thenApplyका उपयोग ऐसे function के साथ करना जो दूसरा CompletableFuture return करे, जिससे एक nested future मिलती है; इसके बजायthenComposeका उपयोग करें।- future के खत्म होने से पहले
mainको खत्म करना, क्योंकि default pool daemon threads का उपयोग करता है और program result print होने से पहले exit हो सकता है।
Chapter Quiz — Complete all 19 topics to unlock
0/19 topics done
Complete these topics first:
- Java Reflection API
- Java Annotations Advanced
- Java Garbage Collection
- Java Memory Management
- Java Performance Optimization
- Java Advanced Interview Questions
- Java CompletableFuture
- Java Atomic Classes
- Java Locks & Semaphores
- Java Concurrent Collections
- Java Cryptography Basics
- Java Hashing (MD5, SHA)
- Java SSL & HTTPS
- Java Logging (Log4j/SLF4J)
- Java Serialization Advanced
- Java Interview Questions Advanced
- Java Connection Pooling
- Java Test Driven Development
- Java Integration Testing