Java Callable और Future
In this page:
Callable<ResultType> task = () -> {
return result;
};
Future<ResultType> future = executor.submit(task);
ResultType result = future.get();
What is Callable?
Callable interface एक asynchronous task को represent करता है, Runnable जैसा ही, लेकिन दो मुख्य अंतरों के साथ: एक Callable अपने call() method से एक computed value return कर सकता है, और यह execution के दौरान checked exceptions फेंक सकता है, जो Runnable का run() नहीं कर सकता।
उदाहरण: What is Callable?
// Import java.util.concurrent.* so it can be used by its short name
import java.util.concurrent.*;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) throws Exception {
Callable<Integer> task = () -> {
if (false) throw new Exception("checked exception allowed");
// Send 5 * 5 back to the caller
return 5 * 5;
};
// Print a line to the console
System.out.println(task.call());
}
}
Login to try C/C++/Java/PHP code in the editor
What is Future?
एक Future किसी executor को submit किए गए asynchronous task के अंतिम, pending result को represent करता है। आप पूर्णता की स्थिति जांचने के लिए इसे isDone() से poll कर सकते हैं, या जवाब तैयार होने तक block करने और उसे निकालने के लिए get() call कर सकते हैं।
उदाहरण: What is Future?
// Import java.util.concurrent.* so it can be used by its short name
import java.util.concurrent.*;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) throws Exception {
// Create a thread pool to run tasks
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(() -> 100);
// Print a line to the console
System.out.println(future.isDone());
// Print a line to the console
System.out.println(future.get());
executor.shutdown();
}
}
Login to try C/C++/Java/PHP code in the editor
Handling Exceptions with Future
अगर कोई Callable task execution के दौरान exception फेंकता है, तो वह exception तुरंत propagate नहीं होता — इसे framework capture करके wrap कर देता है। जब आप बाद में Future.get() call करते हैं, तो यह उस failure को ExecutionException में wrap करके फिर से throw करता है, original exception getCause() के ज़रिए उपलब्ध होता है।
उदाहरण: Handling Exceptions with Future
// Import java.util.concurrent.* so it can be used by its short name
import java.util.concurrent.*;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) throws InterruptedException {
// Create a thread pool to run tasks
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(() -> { throw new RuntimeException("task failed"); });
// Try code that might throw an exception
try {
future.get();
// Handle ExecutionException if it was thrown
} catch (ExecutionException e) {
// Print a line to the console
System.out.println("Caught: " + e.getCause().getMessage());
}
executor.shutdown();
}
}
Login to try C/C++/Java/PHP code in the editor
Multiple Callables with invokeAll()
आप किसी ExecutorService के invokeAll() method का उपयोग करके कई Callable tasks को parallel में चला सकते हैं, जो हर task को एक साथ submit करता है और जब तक वे सभी पूरे न हो जाएं तब तक block करता है। यह उसी order में Future objects की एक List return करता है जिस order में tasks submit किए गए थे, आपको हर result अलग-अलग निकालने देते हुए।
उदाहरण: Multiple Callables with invokeAll()
// Import java.util.* so it can be used by its short name
import java.util.*;
// Import java.util.concurrent.* so it can be used by its short name
import java.util.concurrent.*;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) throws Exception {
// Create a thread pool to run tasks
ExecutorService executor = Executors.newFixedThreadPool(2);
List<Callable<Integer>> tasks = List.of(() -> 1 + 1, () -> 2 + 2, () -> 3 + 3);
List<Future<Integer>> results = executor.invokeAll(tasks);
for (Future<Integer> f : results) System.out.println(f.get());
executor.shutdown();
}
}
Login to try C/C++/Java/PHP code in the editor
Best Practices with Future
अपने application को किसी hung task पर अनिश्चित काल तक block होने से रोकने के लिए, बिना-argument वाले overload को call करने के बजाय हमेशा Future.get(timeout, unit) को एक timeout पास करें। यह भी अच्छी practice है कि हर executor service को एक finally block के अंदर shut down करें ताकि यह किसी task के throw करने पर भी release हो जाए।
उदाहरण: Best Practices with Future
// Import java.util.concurrent.* so it can be used by its short name
import java.util.concurrent.*;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Create a thread pool to run tasks
ExecutorService executor = Executors.newSingleThreadExecutor();
// Try code that might throw an exception
try {
Future<Integer> future = executor.submit(() -> 42);
// Print a line to the console
System.out.println(future.get(2, TimeUnit.SECONDS));
// Handle Exception if it was thrown
} catch (Exception e) {
// Print a line to the console
System.out.println("Timed out or failed");
} finally {
executor.shutdown();
}
}
}
Login to try C/C++/Java/PHP code in the editor
future.get()को बिना timeout के call करना, जिससे अगर task हैंग हो जाए तो program हमेशा के लिए block हो सकता है;get(timeout, unit)का उपयोग करें।- सिर्फ task के exception type को catch करना, जबकि
get()इसे एकExecutionExceptionमें wrap करता है और आपकोe.getCause()पढ़ना चाहिए। - यह भूल जाना कि
get()जवाब तैयार होने तक block करता है, और इसे सभी tasks submit करने से पहले main thread पर call करना, जो parallelism हटा देता है।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: