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.
Use a pool of 4 threads to compute the squares of 1..8 as Callables and print them in order.
Use invokeAny to return whichever of two tasks finishes first.
Explain it without notes
Why use a thread pool instead of creating a thread per task?
What happens to an exception thrown inside a task submitted with submit()?
How do you shut down an executor correctly?
Expected output
heartbeat 1
heartbeat 2
heartbeat 3
stopped after 3 heartbeats