Callable and Future
- Java course
- Advanced
- Lesson 62/82
- 5 min
Learn result-bearing tasks with Callable and Future.
Callable and Future
Callable<V> is a task interface that returns a result. Unlike Runnable, its call() method returns a value and can throw checked exceptions. Future<V> lets you get the result when ready.
Callable<Integer> task = () -> 2 + 3;
Future<Integer> f = pool.submit(task);
Integer result = f.get();get() waits until the task finishes. get(timeout, unit) throws TimeoutException after a duration. This is used to skip unresponsive tasks. On error you get ExecutionException; the cause is available via getCause().
Timeout with get
Future.get(long, TimeUnit) waits up to a duration; if exceeded, TimeoutException is thrown. This is used to skip unresponsive tasks.
try {
Integer r = f.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
f.cancel(true);
}cancel(true) interrupts the task. This protects the system during long-running operations. isDone() asks whether the task is finished. These controls are critical in production concurrent code.
Practice Get a result with Callable
Write main in a CallableDemo class; create a pool with Executors.newSingleThreadExecutor(). Define Callable<Integer> task = () -> 6 * 7; submit it with pool.submit(task) to get a Future<Integer>. Print f.get() with System.out.println. Finally call pool.shutdown().
Starter code
import java.util.concurrent.*;
// Write main in CallableDemo
// Define a Callable task (return 6*7)
// Get a Future via submit; print get; call shutdownSample solution
import java.util.concurrent.*;
class CallableDemo {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
Callable<Integer> task = () -> 6 * 7;
Future<Integer> f = pool.submit(task);
System.out.println(f.get());
pool.shutdown();
}
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the Callable method
Callable<Integer> task = () -> 2 + 3;
Future<Integer> f = pool.submit(task);
Integer result = f.____();
Callable<Integer> task = () -> 2 + 3;
Future<Integer> f = pool.submit(task);
Integer result = f.get();
Explanation: Future.get() waits for the result.
2 What happens when Future.get() is called?
- Returns the result immediately
- Cancels the task
- Restarts the task
- Blocks the caller until the task finishes Correct answer
Explanation: get() blocks the caller until the task finishes.
3 Match Callable/Future concepts
| Term | Meaning |
|---|---|
Callable |
Task returning a result |
Future |
Represents the result |
get() |
Waits and fetches |
cancel() |
Cancels the task |