Callable and Future
Callable is similar to Runnable, but its task can return a result and can throw a checked exception. Future represents the eventual result of a Callable task, which may still be running in the background when you first receive it.
1. What are Callable and Future?
Callable is similar to Runnable, but its task can return a result and can throw a checked exception. Future represents the eventual result of a Callable task, which may still be running in the background when you first receive it.
2. Why is it used?
Runnable cannot return a value, but many real tasks need to produce a result — like a calculation running in the background whose result you need later. Callable and Future together support this "run now, collect result later" pattern.
3. Real-Life Example
Think of placing an online order and receiving a tracking number (the Future) immediately, without waiting for the actual delivery. Later, you can check the tracking number to see if your order (the actual result) has arrived.
4. Syntax
javaCallable<ResultType> task = () -> { return result; }; Future<ResultType> future = executor.submit(task); ResultType result = future.get(); // waits for and retrieves the result
5. Example Program
javaimport java.util.concurrent.*; public class CallableFutureDemo { public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<Integer> task = () -> { return 10 * 10; }; Future<Integer> future = executor.submit(task); System.out.println("Result: " + future.get()); executor.shutdown(); } }
Output:
Result: 1006. Key Points to Remember
Callablereturns a value;Runnabledoes not.future.get()blocks (waits) until the result is ready, unless you checkisDone()first.Callablecan throw checked exceptions, unlikeRunnable'srun()method.