Command Palette

Search for a command to run...

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

A scheduled task with a fixed delay

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?

A scheduled task with a fixed delay Java 5+
Sign in to run this example in your browser.

Expected output

heartbeat 1
heartbeat 2
heartbeat 3
stopped after 3 heartbeats