Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 12 / Topic 3 of 7

ExecutorService, Callable and Future

Creating a brand-new Thread for every task (section 1) doesn't scale — thousands of short tasks would mean thousands of OS threads, each with real memory and scheduling overhead. An ExecutorService is a thread pool: a fixed (or bounded) set of worker threads that pull tasks off a queue, reused across many submissions. Think of a fixed number of billing clerks sharing one queue of invoices, instead of hiring a brand-new clerk for every single invoice and firing them the moment it's done.

Callable<V> is Runnable's cousin: it returns a value (and can throw a checked exception). Submitting a Callable gives you a Future<V> — a handle to a result that may not exist yet. future.get() blocks until the task finishes (or re-throws, wrapped, if the task threw).

ExecutorService pool = Executors.newFixedThreadPool(4);
List<Future<String>> futures = pool.invokeAll(tasks);   // submits all, returns Futures in the same order
for (Future<String> future : futures) {
    System.out.println(future.get());        // blocks until THIS task is done
}
pool.shutdown();                              // accept no new tasks; let running ones finish
pool.awaitTermination(5, TimeUnit.SECONDS);
$ javac ExecutorServiceDemo.java
$ java ExecutorServiceDemo
== a fixed thread pool, 4 tasks of 200 ms, submitted together ==
Asha    12.5 kg -> Rs. 1,187.50
Ravi     8.0 kg -> Rs. 760.00
Meera   20.0 kg -> Rs. 1,900.00
Kabir    5.5 kg -> Rs. 522.50
4 tasks of 200 ms on 4 threads finished in under 600 ms: true

== a task that throws: Future.get() re-throws it, wrapped ==
caught: NumberFormatException: For input string: "not-a-number"
pool terminated cleanly: true

Four 200 ms tasks on four threads finish in roughly 200 ms total, not 800 ms — the whole point of a pool sized to the available parallelism. A task that throws doesn't crash anything at submission time; the exception is captured and re-thrown from future.get() wrapped in an ExecutionException, with the original failure reachable through getCause() — the same wrap-and-rethrow discipline Part 11 used for your own exceptions.

pool.shutdown() stops the pool from accepting new work but lets already-running tasks finish; pool.shutdownNow() (used in section 4's example) attempts to cancel running tasks too. An ExecutorService that's never shut down leaves its worker threads running, which — unlike a plain background Thread — will keep the JVM alive after main returns.

Full program: examples/ExecutorServiceDemo.java.

Done here? The practice set for Part 12 — including the solutions — is on the part page.

Search the guide