Your own executor and timeouts
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Real async code talks to slow things: databases, payment gateways, other servers. Such work belongs on your own executor, and every call to the outside world needs a timeout, so one slow server cannot hold up the whole app.
Why blocking I/O should not use the common pool
Blocking I/O is work where a thread waits for something outside the program, such as a database, a network call or a file, and does nothing while it waits.
Example 1 · Twenty slow calls: common pool versus an I/O pool
import java.util.List;import java.util.concurrent.CompletableFuture;import java.util.concurrent.Executor;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ForkJoinPool;import java.util.stream.IntStream;
public class StarvedPoolDemo { static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
static long runCalls(int count, Executor executor) { warmUp(count, executor); long start = System.currentTimeMillis(); List<CompletableFuture<Void>> calls = IntStream.rangeClosed(1, count) .mapToObj(i -> CompletableFuture.runAsync(() -> sleep(100), executor)) // 100 ms DB call .toList(); CompletableFuture.allOf(calls.toArray(new CompletableFuture[0])).join(); return Math.round((System.currentTimeMillis() - start) / 100.0) * 100; }
static void warmUp(int count, Executor executor) { // start the pool threads first List<CompletableFuture<Void>> calls = IntStream.rangeClosed(1, count) .mapToObj(i -> CompletableFuture.runAsync(() -> sleep(10), executor)) .toList(); CompletableFuture.allOf(calls.toArray(new CompletableFuture[0])).join(); }
public static void main(String[] args) { System.out.println("Common pool threads: " + ForkJoinPool.commonPool().getParallelism()); System.out.println("20 calls on the common pool: about " + runCalls(20, ForkJoinPool.commonPool()) + " ms");
ExecutorService ioPool = Executors.newFixedThreadPool(20); System.out.println("20 calls on a 20-thread pool: about " + runCalls(20, ioPool) + " ms"); ioPool.shutdown(); }}Common pool threads: 11 20 calls on the common pool: about 200 ms 20 calls on a 20-thread pool: about 100 ms
What this code does
- With 11 common pool threads (a 12-core machine), 20 calls need two rounds of 100 ms. On an 8-core laptop the pool has 7 threads and needs three rounds, so your numbers will differ.
- The 20-thread pool runs every call at once. While the common pool was busy sleeping, any other async step in the program would have had to wait.
The common pool is a poor place for it: it is small (cores - 1 threads) and shared by every CompletableFuture and parallel stream in the program. A handful of slow calls can occupy every common pool thread. Then all other async work, even quick steps, waits in a queue behind them. This is called starving the pool.
Earlier lessons put Thread.sleep in the common pool to keep examples short. In real code, give I/O its own pool, sized for how many calls you want waiting at once.
Passing an executor to supplyAsync and the Async methods
supplyAsync(supplier, executor) runs the task on the executor you pass instead of the common pool. runAsync(runnable, executor) and every Async step, such as thenApplyAsync(fn, executor), take an executor as their last argument too.
Example 2 · One pool for the database, one for calculations
import java.util.List;import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;
public class TwoPoolsDemo { static String thread() { return Thread.currentThread().getName(); }
public static void main(String[] args) { ExecutorService dbPool = Executors.newSingleThreadExecutor(r -> new Thread(r, "db-1")); ExecutorService cpuPool = Executors.newSingleThreadExecutor(r -> new Thread(r, "cpu-1"));
try { String report = CompletableFuture .supplyAsync(() -> { System.out.println("fetch marks on " + thread()); return List.of(78, 85, 91, 66, 88); }, dbPool) .thenApplyAsync(marks -> { System.out.println("compute average on " + thread()); return marks.stream().mapToInt(Integer::intValue).average().orElse(0); }, cpuPool) .thenApply(avg -> "Class average: " + avg) .join(); System.out.println(report); } finally { dbPool.shutdown(); cpuPool.shutdown(); } }}fetch marks on db-1 compute average on cpu-1 Class average: 81.6
What this code does
- The second argument picks the pool: the fetch runs on
db-1, the calculation oncpu-1. Each pool's thread factoryr -> new Thread(r, "db-1")names its thread. - Both pools are shut down in
finally, so the program ends even if a step throws.
Example 3 · A named I/O pool for many PNR checks
import java.util.List;import java.util.Set;import java.util.TreeSet;import java.util.concurrent.CompletableFuture;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.atomic.AtomicInteger;import java.util.stream.IntStream;
public class NamedIoPoolDemo { static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
public static void main(String[] args) { AtomicInteger counter = new AtomicInteger(); ExecutorService io = Executors.newFixedThreadPool(4, r -> new Thread(r, "io-" + counter.incrementAndGet())); Set<String> usedThreads = ConcurrentHashMap.newKeySet();
try { List<CompletableFuture<String>> checks = IntStream.rangeClosed(1, 8) .mapToObj(i -> CompletableFuture.supplyAsync(() -> { usedThreads.add(Thread.currentThread().getName()); sleep(50); // railway server call return "PNR-" + i + ": CNF"; }, io)) .toList();
checks.forEach(c -> System.out.println(c.join())); System.out.println("Threads used: " + new TreeSet<>(usedThreads)); } finally { io.shutdown(); } }}PNR-1: CNF PNR-2: CNF PNR-3: CNF PNR-4: CNF PNR-5: CNF PNR-6: CNF PNR-7: CNF PNR-8: CNF Threads used: [io-1, io-2, io-3, io-4]
What this code does
- A fixed pool of 4 runs the 8 checks in two rounds. The thread factory counts up, so the threads are called
io-1toio-4instead ofpool-1-thread-3. - Results print in list order because each
join()reads its own future. The thread names are collected in a thread-safe set and sorted for printing.
A common setup is one pool per kind of work: an I/O pool with more threads for waiting calls, and a small pool, or the common pool, for quick calculations. Giving the threads names, through a thread factory, makes logs and thread dumps much easier to read. The plain steps (thenApply, thenAccept) still run on whichever thread completes the stage before them, which is often a thread of your pool.
orTimeout and completeOnTimeout
A timeout is a time limit for a result. If the future is not done in time, orTimeout fails it with a TimeoutException, and completeOnTimeout completes it with a fallback value instead.
orTimeout(time, unit) makes a future fail with a TimeoutException if it is not done within the time. completeOnTimeout(value, time, unit) completes it with a fallback value instead. Both were added in Java 9 and both return the same future, so you can keep chaining.
Example 4 · orTimeout: a slow vendor becomes an error
import java.util.concurrent.CompletableFuture;import java.util.concurrent.CompletionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
public class OrTimeoutDemo { static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
static Throwable unwrap(Throwable ex) { if (ex instanceof CompletionException && ex.getCause() != null) { return ex.getCause(); } return ex; }
public static void main(String[] args) { ExecutorService io = Executors.newFixedThreadPool(2); try { String price = CompletableFuture.supplyAsync(() -> { sleep(200); // slow vendor return "Rs 349"; }, io) .orTimeout(50, TimeUnit.MILLISECONDS) .thenApply(p -> "Price: " + p) .exceptionally(ex -> "Vendor failed: " + unwrap(ex).getClass().getSimpleName()) .join(); System.out.println(price); } finally { io.shutdown(); } }}Vendor failed: TimeoutException
What this code does
- After 50 ms the vendor has not answered, so
orTimeoutfails the future with aTimeoutException. ThethenApplyis skipped andexceptionallyturns the error into a message. - The vendor task is still sleeping when the message prints.
shutdown()lets it finish its last 150 ms, and then the JVM exits.
Example 5 · completeOnTimeout: a default price, and the late reply
import java.util.List;import java.util.concurrent.CompletableFuture;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
public class CompleteOnTimeoutDemo { static CountDownLatch slowServer = new CountDownLatch(1); // ShopC answers only when released
static CompletableFuture<String> quote(String shop, String price, boolean slow, ExecutorService io) { return CompletableFuture.supplyAsync(() -> { if (slow) { try { slowServer.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } System.out.println("(" + shop + " replied late, ignored)"); } return shop + " Rs " + price; }, io).completeOnTimeout(shop + " N/A", 500, TimeUnit.MILLISECONDS); }
public static void main(String[] args) throws InterruptedException { ExecutorService io = Executors.newFixedThreadPool(3); try { List<CompletableFuture<String>> quotes = List.of( quote("ShopA", "349", false, io), quote("ShopB", "299", false, io), quote("ShopC", "279", true, io)); CompletableFuture.allOf(quotes.toArray(new CompletableFuture[0])).join(); quotes.forEach(q -> System.out.println(q.join())); slowServer.countDown(); // ShopC finally answers } finally { io.shutdown(); io.awaitTermination(1, TimeUnit.SECONDS); } System.out.println("All tasks finished"); }}ShopA Rs 349 ShopB Rs 299 ShopC N/A (ShopC replied late, ignored) All tasks finished
What this code does
- ShopA and ShopB answer at once. ShopC is stuck (the latch stands in for a server that hangs), so after 500 ms
completeOnTimeoutfills its future withShopC N/Aand the page can show all three quotes. - The ShopC task was not stopped: when the latch is released it prints its late line, and its price is ignored.
awaitTerminationwaits for it beforemainprints the last line.
Use orTimeout when a late answer is an error the caller must handle, and completeOnTimeout when a default is fine, such as "price not available" from one of several shops. Neither method stops the slow task. It keeps running on its thread until it finishes, and its late result is ignored. That is one more reason to keep slow calls on your own pool.
orTimeout receives the plain TimeoutException; one step later it is wrapped in a CompletionException. Use the unwrap helper from lesson 6.Shutting down the executor afterwards
Shutting down an executor tells it to accept no new tasks and to end its threads once the queued tasks are done. Threads from Executors.newFixedThreadPool are not daemon threads, so a pool you forget to shut down keeps the JVM running after main ends.
// Java 21import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;
public class CloseablePoolDemo { public static void main(String[] args) { try (ExecutorService pool = Executors.newFixedThreadPool(2)) { CompletableFuture<Integer> fare = CompletableFuture.supplyAsync(() -> 1450, pool); System.out.println("Fare: Rs " + fare.join()); } // close(): shutdown, then wait for the tasks System.out.println("Pool closed"); }}Fare: Rs 1450 Pool closed
On Java 17, call shutdown() in a finally block, then awaitTermination if you must wait for running tasks. From Java 19, ExecutorService also works in try-with-resources: close() shuts the pool down and waits for its tasks.
Example 6 · The full pattern: own pool, timeouts, combine, shut down
import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;
public class TripQuoteDemo { static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
static int trainFare() { return 1450; }
static int hotelPrice() { sleep(200); // hotel site is very slow today return 2200; }
public static void main(String[] args) throws InterruptedException { AtomicInteger n = new AtomicInteger(); ExecutorService io = Executors.newFixedThreadPool(4, r -> new Thread(r, "trip-io-" + n.incrementAndGet())); try { CompletableFuture<Integer> fare = CompletableFuture.supplyAsync(() -> trainFare(), io) .orTimeout(500, TimeUnit.MILLISECONDS); // fare is required CompletableFuture<Integer> hotel = CompletableFuture.supplyAsync(() -> hotelPrice(), io) .completeOnTimeout(2500, 100, TimeUnit.MILLISECONDS); // estimate is fine
String quote = fare.thenCombine(hotel, (f, h) -> "Trip estimate: Rs " + (f + h) + (h == 2500 ? " (hotel price estimated)" : "")) .exceptionally(ex -> "Cannot quote: train fare unavailable") .join(); System.out.println(quote); } finally { io.shutdown(); io.awaitTermination(1, TimeUnit.SECONDS); } System.out.println("Pool shut down: " + io.isTerminated()); }}Trip estimate: Rs 3950 (hotel price estimated) Pool shut down: true
What this code does
- The two timeouts say what each value means to the business: no fare means no quote (
orTimeout), while a hotel estimate of Rs 2500 is acceptable (completeOnTimeout). The fare comes from a cache, so it answers at once. shutdown()andawaitTerminationinfinallylet the slow hotel task finish and end the pool's threads, soisTerminated()istrueand the JVM can exit.
Next step
Check your understanding
12 quick questions