Callable and Future
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A Runnable task cannot hand back a result. But you often need one: a price from a server, a total from a long calculation. How do you start the work and collect the answer later?
Callable returns a value and may throw
A Callable is a task that returns a result and may throw an exception; a Future is a handle to that result, which get() waits for.
Callable<V> is a functional interface with one method, V call() throws Exception. Unlike Runnable.run(), it returns a result, and it is allowed to throw checked exceptions such as IOException.
Example 1 · Two sections' marks totalled in parallel
import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
public class SectionTotalsDemo { static int total(List<Integer> marks) { int sum = 0; for (int m : marks) { sum += m; } return sum; }
public static void main(String[] args) throws InterruptedException, ExecutionException { List<Integer> sectionA = List.of(78, 91, 66, 85); List<Integer> sectionB = List.of(55, 72, 98, 81, 60);
ExecutorService pool = Executors.newFixedThreadPool(2); Callable<Integer> taskA = () -> total(sectionA); Future<Integer> futureA = pool.submit(taskA); Future<Integer> futureB = pool.submit(() -> total(sectionB));
int a = futureA.get(); // waits if section A is not done yet int b = futureB.get(); System.out.println("Section A total: " + a); System.out.println("Section B total: " + b); System.out.println("Both sections: " + (a + b)); pool.shutdown(); }}Section A total: 320 Section B total: 366 Both sections: 686
What this code does
taskAis written out as aCallable<Integer>; for section B the lambda is passed directly, and because it returns a value,submittreats it as aCallabletoo.- Both totals are computed at the same time on two pool threads.
get()hands each result back to main, already typed asInteger.
You rarely write the interface out. A lambda whose body returns a value is a Callable when you pass it to submit: pool.submit(() -> 450 * 12) gives a Future<Integer>. The pool runs call() on one of its threads and keeps the returned value inside the Future. The calling thread is free in the meantime. It can submit more tasks or do its own work and collect the results later.
Future.get() blocks, get with a timeout
get() returns the task's result. If the task has not finished yet, get() blocks: the calling thread stops and waits, as long as it takes.
Example 2 · PNR status with a timeout
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;
public class PnrTimeoutDemo { static String fetchStatus(String pnr) throws InterruptedException { Thread.sleep(200); // the railway server is slow today return pnr + ": CONFIRMED, coach S4, berth 33"; }
public static void main(String[] args) throws Exception { ExecutorService pool = Executors.newFixedThreadPool(1); Future<String> status = pool.submit(() -> fetchStatus("4521876390"));
try { System.out.println(status.get(50, TimeUnit.MILLISECONDS)); } catch (TimeoutException e) { System.out.println("No answer in 50 ms, showing 'Please wait...'"); } System.out.println("Task still running? " + !status.isDone());
System.out.println(status.get()); // now wait as long as it takes pool.shutdown(); }}No answer in 50 ms, showing 'Please wait...' Task still running? true 4521876390: CONFIRMED, coach S4, berth 33
What this code does
get(50, MILLISECONDS)gives up after 50 ms and throwsTimeoutException. The task is not stopped:isDone()is stillfalse.- The second, plain
get()waits for the rest of the 200 ms and returns the status.fetchStatusthrows the checkedInterruptedException, which is allowed because the lambda is aCallable.
get(timeout, unit) waits at most that long. If the result is still not ready, it throws TimeoutException. The task itself keeps running; only the wait has ended. You can try get again later, or cancel the task. A timeout is how you keep a screen responsive when a server is slow: wait a short time, and if there is no answer, show "please wait" or a fallback instead of freezing.
get() right after submit() for each task in turn makes the tasks run one at a time. Submit everything first, then collect.ExecutionException and the real cause
If call() throws, the pool stores that exception in the Future. get() then throws an ExecutionException, and its getCause() returns the exception the task really threw.
Example 3 · Finding the real cause inside ExecutionException
import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
class SeatNotAvailableException extends Exception { SeatNotAvailableException(String message) { super(message); }}
public class RealCauseDemo { static String bookSeat(String seat) throws SeatNotAvailableException { if (seat.equals("F7")) { throw new SeatNotAvailableException("Seat F7 is already booked"); } return "Booked " + seat; }
static void tryBooking(ExecutorService pool, String seat) throws InterruptedException { Future<String> f = pool.submit(() -> bookSeat(seat)); try { System.out.println(f.get()); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof SeatNotAvailableException) { System.out.println("Sorry: " + cause.getMessage()); } else { System.out.println("Unexpected: " + cause); } } }
public static void main(String[] args) throws InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(2); tryBooking(pool, "F6"); tryBooking(pool, "F7"); pool.shutdown(); }}Booked F6 Sorry: Seat F7 is already booked
What this code does
bookSeatthrows a checked exception of our own. That is allowed inside aCallable, but would not compile inside aRunnable.get()wraps it inExecutionException.getCause()returns the originalSeatNotAvailableException, so the program can check its type and show a friendly message.
The wrapping tells you where the problem came from: an ExecutionException means "the task failed", not "get failed". It also lets a task throw any checked exception, which get() can then pass on inside one known type. To react to a specific failure, check the cause: if (e.getCause() instanceof SeatNotAvailableException).
Predict the output
What does get() give back?
Read each snippet and pick what it prints. Each program waits for its tasks.
Round 1 of 2
cancel() and isDone()
isDone() is true once the task has finished in any way: normally, with an exception, or by being cancelled. It never blocks, so you can poll it.
Example 4 · Cancelling a running task and a queued task
import java.util.concurrent.CancellationException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;
public class CancelDemo { static String download(String file) { try { for (int part = 1; part <= 50; part++) { Thread.sleep(20); // one part of the file } return file + " downloaded"; } catch (InterruptedException e) { System.out.println(file + ": download stopped"); return file + " incomplete"; } }
public static void main(String[] args) throws Exception { ExecutorService pool = Executors.newSingleThreadExecutor(); Future<String> notes = pool.submit(() -> download("notes.pdf")); Future<String> video = pool.submit(() -> download("lecture.mp4")); // waits in the queue
Thread.sleep(100); // notes.pdf is running now boolean videoCancelled = video.cancel(false); boolean notesCancelled = notes.cancel(true);
pool.shutdown(); pool.awaitTermination(5, TimeUnit.SECONDS); System.out.println("Cancel video: " + videoCancelled + ", cancel notes: " + notesCancelled); System.out.println("notes done/cancelled: " + notes.isDone() + "/" + notes.isCancelled()); System.out.println("video done/cancelled: " + video.isDone() + "/" + video.isCancelled()); try { notes.get(); } catch (CancellationException e) { System.out.println("get() on notes: CancellationException"); } }}notes.pdf: download stopped Cancel video: true, cancel notes: true notes done/cancelled: true/true video done/cancelled: true/true get() on notes: CancellationException
What this code does
lecture.mp4was still in the queue, socancel(false)removed it and it never started: no "download stopped" line for it.notes.pdfwas running, socancel(true)interrupted its thread, andThread.sleepthrewInterruptedExceptioninside the task.- Both futures are now done and cancelled.
get()on a cancelled future throwsCancellationException, and the value the task returned after the interrupt is thrown away.
cancel(mayInterruptIfRunning) tries to stop the task. A task still waiting in the queue is removed and never runs. A task that is already running is only interrupted, and only with cancel(true). It stops if its code checks for interruption, for example inside Thread.sleep or a blocking call. cancel(false) lets a running task finish. After a successful cancel, isCancelled() and isDone() are both true, and get() throws CancellationException. cancel returns false if the task had already finished.
Runnable versus Callable
Both describe a task. Pick by what the task must give back.
Runnable printTicket = () -> System.out.println("PNR 4521: printed"); // no resultCallable<Integer> fare = () -> 1450 + 45; // returns 1495
Callable<String> status = () -> { Thread.sleep(100); // checked exception: fine in call() return "CONFIRMED";};// Runnable r = () -> Thread.sleep(100); // does not compile:// unreported exception InterruptedException; must be caught or declared to be thrownRunnable.run()returnsvoidand cannot throw checked exceptions.Callable.call()returns aVand may throw anyException.- A
Runnableworks withnew Thread(...),executeandsubmit. ACallableworks withsubmitandinvokeAll/invokeAny, not withnew Thread(...). submit(runnable)gives aFuture<?>whoseget()returnsnull.submit(callable)gives aFuture<V>with the real result.Executors.callable(runnable, result)wraps aRunnableinto aCallablethat returns the given result.
Fix the error
Make the task compile
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
The task sleeps for 100 ms before it finishes.
Error
FareDemo.java:6: error: unreported exception InterruptedException; must be caught or declared to be thrown
Runnable fetch = () -> Thread.sleep(100);
^Example 5 · Result card from four subject servers
import java.util.LinkedHashMap;import java.util.Map;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;
public class ResultCardDemo { static int fetchMarks(String subject, int delayMs, int marks) throws Exception { Thread.sleep(delayMs); if (marks < 0) { throw new Exception(subject + " server down"); } return marks; }
public static void main(String[] args) throws InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(4); Map<String, Future<Integer>> results = new LinkedHashMap<>(); results.put("Maths", pool.submit(() -> fetchMarks("Maths", 60, 88))); results.put("Physics", pool.submit(() -> fetchMarks("Physics", 30, 79))); results.put("Chemistry", pool.submit(() -> fetchMarks("Chemistry", 20, -1))); results.put("English", pool.submit(() -> fetchMarks("English", 2000, 91)));
int total = 0; for (Map.Entry<String, Future<Integer>> e : results.entrySet()) { Future<Integer> f = e.getValue(); try { int marks = f.get(300, TimeUnit.MILLISECONDS); total += marks; System.out.println(e.getKey() + ": " + marks); } catch (ExecutionException ex) { System.out.println(e.getKey() + ": error (" + ex.getCause().getMessage() + ")"); } catch (TimeoutException ex) { f.cancel(true); System.out.println(e.getKey() + ": pending (timed out)"); } } System.out.println("Total of available marks: " + total); pool.shutdown(); }}Maths: 88 Physics: 79 Chemistry: error (Chemistry server down) English: pending (timed out) Total of available marks: 167
What this code does
- All four requests run at the same time. Results are read in a fixed order through a
LinkedHashMap, so the output order does not depend on which server answered first. - Each
gethandles all three outcomes: a value, a failure (ExecutionExceptionwith the real cause) and a slow server (TimeoutException, thencancel(true)so the thread is not wasted).
Next step
Check your understanding
12 quick questions