Module 10 · Lambdas, Streams, Concurrency and JDBC — topic 3 of 5
Multithreading and Executors
Threads and the Runnable and Callable interfaces, starting and joining threads, thread states, ExecutorService thread pools, Futures, CompletableFuture and virtual threads (Java 21).
Learning objectives
- Create and start threads with Runnable and lambdas, and wait for them with join
- Submit tasks to an ExecutorService and collect results with Future
- Explain when concurrency helps and what virtual threads are
Definition
A thread is an independent path of execution within a program. Multithreading runs several threads concurrently so that work can overlap — using several CPU cores, or continuing while waiting for I/O. An ExecutorService manages a pool of threads that execute submitted tasks.
Introduction
A web server handles thousands of requests at once; a desktop app stays responsive while it downloads a file; a data job uses all eight cores to finish eight times faster. All of these rely on threads. Java has supported threads since version 1.0, and modern Java adds higher-level tools that make them far easier to use correctly.
Why it matters
Server-side Java is fundamentally concurrent, and concurrency questions appear in most backend interviews.
Using several cores can turn a slow batch job into a fast one.
Detailed explanation
Creating threads. Pass a Runnable (a task with void run()) to new Thread(task) and call start(). start creates a new thread that calls run; calling run() directly just runs the code in the current thread.
Waiting. t.join() blocks until thread t finishes. Without joins, main may finish (or print) before the worker threads do. Thread.sleep(ms) pauses the current thread; both throw the checked InterruptedException.
Scheduling is unpredictable. The order in which runnable threads execute is chosen by the operating system. Output from unsynchronised threads can interleave differently on every run — programs must not depend on it.
Thread states. NEW → RUNNABLE → (BLOCKED / WAITING / TIMED_WAITING) → TERMINATED.
Executors. Creating a thread per task is expensive. ExecutorService pool = Executors.newFixedThreadPool(4) reuses a fixed set of threads. submit(callable) returns a Future<T>; future.get() waits for the result. invokeAll runs a list of tasks. Always shutdown() the pool (or use try-with-resources on Java 19+, where ExecutorService is AutoCloseable).
Callable<T> is like Runnable but returns a value and may throw checked exceptions.
CompletableFuture composes asynchronous steps: supplyAsync(...).thenApply(...).thenCombine(...).
Virtual threads (Java 21) are lightweight threads managed by the JVM: Executors.newVirtualThreadPerTaskExecutor() can run hundreds of thousands of blocking tasks (such as network calls) cheaply. Platform threads remain best for CPU-heavy work.
Syntax
- Call start(), not run(), to create a new thread.
- join() and get() wait; sleep() pauses; all can be interrupted.
- Never rely on the order in which unsynchronised threads print.
Code examples
Starting and joining threads
worker-0 summed 500500 worker-1 summed 1500500 worker-2 summed 2500500 total 4501500, state of worker-0: TERMINATED
The threads may finish in any order, but the program prints only after join, in a fixed order, so its output is always the same.
start() versus run()
task runs on: main thread task runs on: a new thread
More examples
Thread pools, Futures and CompletableFuture
chunk 0: 5133 primes chunk 1: 4459 primes chunk 2: 4256 primes chunk 3: 4136 primes primes below 200000: 17984 total with tax: 1416 reply 1 reply 2 reply 3
Step-by-step explanation
- The range 0–200,000 is split into four chunks, each counted by a
Callable<Integer>that returns its result. invokeAllsubmits all tasks to a pool of four threads and waits until they are done, returning Futures in the same order as the tasks.futures.get(c).get()retrieves each result; printing them in task order keeps the output deterministic even though the chunks ran in parallel.thenCombinewaits for two asynchronous values and merges them;thenApplytransforms the combined result.- The virtual-thread executor runs each blocking task (sleeping 50 ms) on its own lightweight thread; the try-with-resources block waits for them and shuts the executor down.
Expected output
Running “Thread pools, Futures and CompletableFuture” prints exactly:
Practical applications
- Web servers handling many requests concurrently
- Parallel batch processing of files, images or reports
- Calling several remote services at once and combining their answers
- Background tasks such as autosave and periodic clean-up
Best practices
- Use executors instead of creating raw threads for many tasks.
- Make tasks independent; return results rather than sharing variables.
- Use virtual threads for many blocking I/O tasks and fixed pools sized to CPU cores for computation.
Common mistakes
Calling run() instead of start()
Avoid
Prefer
run() is an ordinary method call; only start() creates a new thread of execution.
Forgetting to shut down an executor
Avoid
Prefer
Pool threads keep the JVM alive; call shutdown() or, on Java 19+, use try-with-resources.
Important notes
- ExecutorService became AutoCloseable in Java 19; virtual threads became standard in Java 21.
- Timing-dependent output (such as which thread finishes first) varies between runs; the examples here only print results in a fixed order.
Key takeaways
- start() runs a Runnable on a new thread; join() waits for it.
- ExecutorService pools threads; submit returns a Future whose get() waits for the result.
- CompletableFuture composes async steps; virtual threads make blocking tasks cheap.
Try it yourself
- 1Use a fixed thread pool to compute the sum of squares of 1..1,000,000 in four parts.
- 2Simulate downloading five files with sleep, first sequentially and then with an executor, and compare the elapsed time.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
4 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is the difference between calling t.start() and t.run() on a Thread?
- ModerateWhat is printed?
- AdvancedWhat is printed?