Java
Callable and Future
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.
Exercise 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().
Show example 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();
}
}
Test yourself
-
Complete the Callable method
Callable<Integer> task = () -> 2 + 3;
Future<Integer> f = pool.submit(task);
Integer result = f.____();
Show answer
Callable<Integer> task = () -> 2 + 3;
Future<Integer> f = pool.submit(task);
Integer result = f.get();
-
What happens when Future.get() is called?
- Returns the result immediately
- Cancels the task
- Restarts the task
- Blocks the caller until the task finishes
Show answer
Blocks the caller until the task finishes — get() blocks the caller until the task finishes.
-
Match Callable/Future concepts
- Callable
- Task returning a result
- Future
- Represents the result
- get()
- Waits and fetches
- cancel()
- Cancels the task
Next lesson: CompletableFuture