Command Palette

Search for a command to run...

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

Futures collected in submission order

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?

Futures collected in submission order Java 5+
Sign in to run this example in your browser.

Expected output

part 0: 31375
part 1: 93875
part 2: 156375
part 3: 218875
total: 500500, pool finished: true