Command Palette

Search for a command to run...

Back to the lesson: Topic 13.6 — Executors and Thread Pools
Core Java · Example 2 of 3 Java 9+

invokeAll and a failing task

The failed task didn't kill the pool or the other tasks; its exception waited inside its Future until get() was called.

Instead of creating a thread per task, you hand tasks to an ExecutorService, which runs them on a reusable thread pool and gives back Futures for their results. Pools bound how many threads run at once, reuse threads, and separate *what* to do from *how* it's scheduled.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Use a pool of 4 threads to compute the squares of 1..8 as Callables and print them in order.

02

Use invokeAny to return whichever of two tasks finishes first.

Explain it without notes

01

Why use a thread pool instead of creating a thread per task?

02

What happens to an exception thrown inside a task submitted with submit()?

03

How do you shut down an executor correctly?

invokeAll and a failing task Java 9+
Sign in to run this example in your browser.

Expected output

ok: fetched users
failed: orders service down
ok: fetched prices