Java Callable & Future
In this page:
Callable<ResultType> task = () -> {
return result;
};
Future<ResultType> future = executor.submit(task);
ResultType result = future.get();
What is Callable?
The Callable interface represents an asynchronous task, much like Runnable, but with two key differences: a Callable can return a computed value from its call() method, and it can throw checked exceptions during execution, which Runnable's run() cannot.
Example: 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?
A Future represents the eventual, pending result of an asynchronous task submitted to an executor. You can poll it with isDone() to check completion status, or call get() to block until the result is ready and retrieve it.
Example: 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
If a Callable task throws an exception during execution, that exception doesn't propagate immediately — it's captured by the framework and wrapped. When you later call Future.get(), it re-throws that failure wrapped in an ExecutionException, with the original exception available via getCause().
Example: 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()
You can run multiple Callable tasks in parallel using an ExecutorService's invokeAll() method, which submits every task at once and blocks until all of them complete. It returns a List of Future objects in the same order the tasks were submitted, letting you retrieve each result individually.
Example: 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
To keep your application from blocking indefinitely on a hung task, always pass a timeout to Future.get(timeout, unit) rather than calling the no-argument overload. It's also good practice to shut down every executor service inside a finally block so it's released even if a task throws.
Example: 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
- Calling
future.get()without a timeout, so the program can block forever if the task hangs; useget(timeout, unit). - Catching only the task's exception type, when
get()wraps it in anExecutionExceptionand you must reade.getCause(). - Forgetting that
get()blocks until the result is ready, and calling it on the main thread before submitting all tasks, which removes the parallelism.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: