Java
Module 21: Multithreading & ConcurrencyBeginner28 min read

Threads, Lifecycle, ExecutorService & CompletableFuture

Create threads using Runnable/Thread, understand thread states, avoid calling run() directly, and scale with ExecutorService and CompletableFuture.

Key Takeaways & Core Concepts
  • is an independent OS program with its own isolated virtual address space. A thread is a lightweight unit of execution inside a process: all threads in a JVM share the Heap and Metaspace, while each thread maintains its own private JVM Stack and Program Counter (PC) Register.
  • from the execution mechanism lets you submit tasks to thread pools.
  • Calling t.start() asks the JVM to allocate a new call stack and schedule concurrent execution.
  • Calling t.run() directly is a common bug—it simply executes synchronously on the current thread! Calling t.start() twice throws IllegalThreadStateException.

Process vs Thread

A process is an independent OS program with its own isolated virtual address space. A thread is a lightweight unit of execution inside a process: all threads in a JVM share the Heap and Metaspace, while each thread maintains its own private JVM Stack and Program Counter (PC) Register.

ExecutorService & CompletableFuture Pipeline
1import java.util.concurrent.*;
2
3public class Main {
4 public static void main(String[] args) throws Exception {
5 ExecutorService pool = Executors.newFixedThreadPool(2);
6 Future<String> future = pool.submit(() -> "Computed on " + Thread.currentThread().getName());
7 System.out.println(future.get());
8
9 String asyncResult = CompletableFuture.supplyAsync(() -> "Java", pool)
10 .thenApply(s -> s + " Concurrency")
11 .get();
12 System.out.println(asyncResult);
13 pool.shutdown();
14 }
15}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
15 lines
Note: Always shut down your `ExecutorService` (`pool.shutdown()`) so non-daemon worker threads do not keep the JVM alive.

Thread Lifecycle (Thread.State)

  1. 1
    `NEW`: Thread object created, start() not yet called.
  2. 2
    `RUNNABLE`: Eligible for CPU execution (either running or ready in OS scheduler).
  3. 3
    `BLOCKED`: Waiting to acquire an intrinsic synchronized monitor lock.
  4. 4
    `WAITING` / `TIMED_WAITING`: Paused via Object.wait(), Thread.join(), or Thread.sleep(ms).
  5. 5
    `TERMINATED`: run() completed or threw an uncaught exception.

Thread vs Runnable & start() vs run()

Prefer implementing Runnable (or Callable<V> when returning a value/checked exception) over extending Thread, because Java only allows single class inheritance and separating the task from the execution mechanism lets you submit tasks to thread pools.

  • Calling t.start() asks the JVM to allocate a new call stack and schedule concurrent execution.
  • Calling t.run() directly is a common bug—it simply executes synchronously on the current thread! Calling t.start() twice throws IllegalThreadStateException.

Production Concurrency: ExecutorService & CompletableFuture

Spawning raw new Thread() per HTTP request exhausts OS memory (~1 MB stack per platform thread). Instead, reuse worker threads via ExecutorService (or Java 21 Virtual Threads via Executors.newVirtualThreadPerTaskExecutor()), and compose non-blocking async workflows with CompletableFuture.

Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)