← Back to Advanced Java Course | Chapter 11: Advanced & Security | Lesson 7 of 19

Java का CompletableFuture

CompletableFuture आपको background में एक task शुरू करने और यह बताने देता है कि इसके खत्म होने पर क्या होना चाहिए, जैसे खाना order करना और बताया जाना कि वह कब तैयार है। आप steps को साथ chain कर सकते हैं।
Syntax
java
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?

java
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
	}
}

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()

java
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();
	}
}

SupplyAsync and Callbacks

supplyAsync() एक task चलाता है जो asynchronously एक result produce करता है, और इसके output को thenAccept() से chain करना आपको उस completed value को process करने देता है जब वह तैयार हो, chain में कहीं भी calling thread को block किए बिना।

उदाहरण: SupplyAsync and Callbacks

java
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
	}
}

Combining Futures

thenCombine() आपको दो स्वतंत्र CompletableFutures को combine करने और उनके दोनों results को साथ process करने देता है जैसे ही वे दोनों खत्म हो जाएं, जो तब उपयोगी है जब दो असंबंधित async operations (जैसे दो अलग API calls) दोनों के पूरा होने के बाद ही आप आगे बढ़ सकें।

उदाहरण: Combining Futures

java
// 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());
	}
}

Exception Handling

exceptionally() आपको async background tasks की किसी chain के अंदर कहीं भी फेंकी गई errors को पकड़ने और handle करने देता है, एक सुरक्षित fallback value देने देते हुए बजाय exception के uncaught propagate होकर पूरे async pipeline को चुपचाप fail करने के।

उदाहरण: Exception Handling

java
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());
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. supplyAsync के ठीक बाद get() या join() call करना, जो thread को block करता है और asynchronous होने का फायदा हटा देता है।
  2. thenApply का उपयोग ऐसे function के साथ करना जो दूसरा CompletableFuture return करे, जिससे एक nested future मिलती है; इसके बजाय thenCompose का उपयोग करें।
  3. future के खत्म होने से पहले main को खत्म करना, क्योंकि default pool daemon threads का उपयोग करता है और program result print होने से पहले exit हो सकता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.