Topic 5.1
Java Concurrency Primitives
In one line
Thread, Process, Runnable, Callable, Future — the units and handles of concurrent work.
Think of it like this
A restaurant kitchen. A Process is a separate kitchen with its own ingredients (isolated); a Thread is a chef working inside the same kitchen, sharing the same fridge and counters (shared memory) as other chefs.
Key ideas
- 01
Process = separate memory space (isolation, heavier); Thread = lightweight unit inside a process sharing heap.
- 02
Runnable: void run() — fire and forget; Callable<V>: V call() throws Exception — can return a value.
- 03
Future<V> is the handle: submit a Callable, later call future.get() (blocks) or future.isDone().
- 04
Modern Java: CompletableFuture for composition; virtual threads (Project Loom, Java 21+) make threads nearly free.
- 05
How many threads? CPU-bound ≈ cores; IO-bound >> cores (each thread waits on IO). Spring Boot 3.2+ default uses virtual threads on Tomcat.
Java / Spring map
- →
Executors; CompletableFuture.supplyAsync; Thread.startVirtualThread (Java 21+).
Code & diagrams
Thread vs Runnable vs Callable+Future in one small program.
Runnable task = () -> System.out.println("fire & forget: " + Thread.currentThread());
Callable<Integer> compute = () -> {
Thread.sleep(100); // pretend work
return 6 * 7;
};
ExecutorService pool = Executors.newFixedThreadPool(4);
pool.execute(task); // Runnable — no result
Future<Integer> f = pool.submit(compute); // Callable — result handle
int answer = f.get(); // blocks until done
// Java 21+:
// try (var p = Executors.newVirtualThreadPerTaskExecutor()) { p.submit(task); }Explain without notes
When do you need Future/Callable over Runnable? Give a real LLD scenario (async release of spots?).
Practice
In the Elevator problem, run each elevator as a task that pushes status to a shared dashboard.
Trade-offs
- ↔
Thread-per-task is simple; elastically sized pools + queues are production-grade but tuneable and finicky.
Completion checklist
I can pick Thread / Runnable / Callable / Future for a stated need in one sentence.