Threads, Lifecycle, ExecutorService & CompletableFuture
Create threads using Runnable/Thread, understand thread states, avoid calling run() directly, and scale with ExecutorService and CompletableFuture.
- 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! Callingt.start()twice throwsIllegalThreadStateException.
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.
Thread Lifecycle (Thread.State)
- 1`NEW`:
Threadobject created,start()not yet called. - 2`RUNNABLE`: Eligible for CPU execution (either running or ready in OS scheduler).
- 3`BLOCKED`: Waiting to acquire an intrinsic
synchronizedmonitor lock. - 4`WAITING` / `TIMED_WAITING`: Paused via
Object.wait(),Thread.join(), orThread.sleep(ms). - 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! Callingt.start()twice throwsIllegalThreadStateException.
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.
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)