ThreadLocal & Virtual Threads
ThreadLocal for per-thread state, Project Loom virtual threads (Java 21)
- Use ThreadLocal to avoid shared state in web request contexts
- Create and launch virtual threads with Thread.ofVirtual()
- Understand when virtual threads outperform platform threads
Topics Covered:
ThreadLocal class · Thread-local cleanup · Virtual Threads vs Platform Threads · JVM thread management · Higher throughput · Thread.ofVirtual · Executors.newVirtualThreadPerTaskExecutor
`ThreadLocal` Per-Thread Variable Storage
Overview
ThreadLocal is a Java class that provides thread-local variables — each thread that accesses a ThreadLocal variable has its own, independently initialized copy of that variable. The value stored in a ThreadLocal is private to the thread that set it; no other thread can read or modify that thread's copy.
This is one of Java's key tools for thread isolation without synchronization.
Why This Concept Exists
The Problem It Solves
In a multi-threaded application, sharing mutable state between threads introduces race conditions and requires expensive synchronization mechanisms (synchronized, Lock, etc.). Sometimes, however, you simply need each thread to carry its own private data — data that is specific to that thread's execution context. Examples include:
- A database connection per thread
- A user session or authentication token per request thread
- A formatter object (like
SimpleDateFormat, which is not thread-safe) - A transaction ID associated with the current request
Instead of passing this data as parameters through every method call, or creating separate objects for each thread manually, ThreadLocal provides a clean, built-in mechanism to associate data with the calling thread.
Definition
`ThreadLocal<T>`
is a Java class that provides thread-local storage. Each thread that accesses a ThreadLocal variable (via get() or set()) has its own independently initialized copy of the variable. The type parameter T specifies what kind of data can be stored.
Real-World Analogy
Think of a company with many employees (threads), each of whom has their own desk drawer (ThreadLocal variable). A single memo (the ThreadLocal object) goes out to all desks, and each employee writes their own personal note and stores it in their own drawer. When they come back to read it, they read only their own copy — they never see what their colleagues wrote.
Internal Working
How `ThreadLocal` Works Inside the JVM
Every Java Thread object internally maintains a field called threadLocals, which is of type ThreadLocal.ThreadLocalMap. This is essentially a custom hash map stored inside the Thread object itself.
1Thread Object2└── threadLocals: ThreadLocalMap3 ├── Entry(ThreadLocal<String> key → "main")4 ├── Entry(ThreadLocal<Integer> key → 42)5 └── ...When you call threadLocalObj.set(value):
- JVM calls
Thread.currentThread()to get the currently running thread. - It fetches that thread's
ThreadLocalMap(creating one if it doesn't exist). - It stores the value in the map, using the
ThreadLocalobject itself as the key.
When you call threadLocalObj.get():
- JVM calls
Thread.currentThread(). - It fetches that thread's
ThreadLocalMap. - It looks up the value using the
ThreadLocalobject as the key and returns it.
set() and get() methods always automatically operate on the currently running thread. This is the core elegance of ThreadLocal.Syntax
1// Declaration and creation2ThreadLocal<T> threadLocalVar = new ThreadLocal<>();3
4// Setting a value for the current thread5threadLocalVar.set(value);6
7// Getting the value for the current thread8T value = threadLocalVar.get();9
10// Removing the value for the current thread11threadLocalVar.remove();Syntax Breakdown
| Syntax Element | Explanation |
|---|---|
ThreadLocal | Generic class; T is the type of data to store (e.g., String, Integer, or any object) |
new ThreadLocal<>() | Creates one ThreadLocal object, shared across threads |
.set(value) | Stores value in the current thread's local storage |
.get() | Retrieves the value from the current thread's local storage |
.remove() | Removes the current thread's value from local storage — critical for cleanup |
Thread.currentThread().getName() | Gets the name of the currently executing thread as a String |
Code Examples
Beginner Example Basic Set and Get
1public class ThreadLocalBasicExample {2
3 // One shared ThreadLocal object for the entire application4 static ThreadLocal<String> threadLocal = new ThreadLocal<>();5
6 public static void main(String[] args) throws InterruptedException {7
8 // The main thread sets its own value9 threadLocal.set(Thread.currentThread().getName());10 System.out.println("Main thread set: " + threadLocal.get());11
12 // Create a new thread — it will have its own copy13 Thread t1 = new Thread(() -> {14 threadLocal.set(Thread.currentThread().getName());15 System.out.println("Thread t1 set: " + threadLocal.get());16 });17
18 t1.start();19 t1.join();20
21 // Main thread still sees its own value22 System.out.println("Main thread still sees: " + threadLocal.get());23 }24}◆ Output
1Main thread set: main2Thread t1 set: Thread-03Main thread still sees: main◆ Line-by-Line Explanation
| Line | Explanation |
|---|---|
static ThreadLocal | Creates one ThreadLocal object. static means all threads share this single object instance — but each thread has its own value inside it. |
threadLocal.set(Thread.currentThread().getName()) | The main thread calls set(). Java sees the current thread is "main", stores "main" in the main thread's ThreadLocalMap. |
threadLocal.get() in t1 | Thread t1 is now current. Its ThreadLocalMap has "Thread-0" stored. Returns "Thread-0". |
Final threadLocal.get() in main | Main thread is current again. Its map still has "main". Returns "main". |
Intermediate Example Multiple Threads, Same Object
1public class ThreadLocalMultiThread {2
3 static ThreadLocal<String> threadLocal = new ThreadLocal<>();4
5 public static void main(String[] args) throws InterruptedException {6
7 // Main thread sets its name8 threadLocal.set(Thread.currentThread().getName());9
10 Thread t1 = new Thread(() -> {11 threadLocal.set(Thread.currentThread().getName());12 System.out.println("Inside t1: " + threadLocal.get());13 }, "WorkerThread-1");14
15 Thread t2 = new Thread(() -> {16 threadLocal.set(Thread.currentThread().getName());17 System.out.println("Inside t2: " + threadLocal.get());18 }, "WorkerThread-2");19
20 t1.start();21 t2.start();22 t1.join();23 t2.join();24
25 // Main thread retrieves its own value — completely isolated26 System.out.println("Inside main: " + threadLocal.get());27 }28}◆ Output
1Inside t1: WorkerThread-12Inside t2: WorkerThread-23Inside main: mainThreadLocal object, each one sees only its own value. This is the isolation guarantee of ThreadLocal.Memory Representation
1JVM Memory (Heap)2
3┌─────────────────────────────────────────────────────┐4│ Thread: "main" │5│ ┌────────────────────────────────────────────────┐ │6│ │ threadLocals (ThreadLocalMap) │ │7│ │ key: threadLocal object → value: "main" │ │8│ └────────────────────────────────────────────────┘ │9└─────────────────────────────────────────────────────┘10
11┌─────────────────────────────────────────────────────┐12│ Thread: "WorkerThread-1" │13│ ┌────────────────────────────────────────────────┐ │14│ │ threadLocals (ThreadLocalMap) │ │15│ │ key: threadLocal object → value: "WorkerThread-1"│16│ └────────────────────────────────────────────────┘ │17└─────────────────────────────────────────────────────┘18
19┌──────────────────────────┐20│ Heap: ThreadLocal object │ ← shared, one instance21│ (acts as key in maps) │22└──────────────────────────┘The ThreadLocal object itself lives on the heap and is shared. But the values are stored inside each thread's own ThreadLocalMap, giving complete isolation.
Flowchart `threadLocal.set(value)` Execution
Flowchart `threadLocal.get()` Execution
Critical: Cleanup with `ThreadLocal.remove()` in Thread Pools
The Problem Thread Reuse Without Cleanup
This is one of the most important practical pitfalls with ThreadLocal. It is directly relevant to thread pool usage (e.g., ThreadPoolExecutor).
The Scenario
In a thread pool (e.g., Executors.newFixedThreadPool(5)), a fixed number of threads execute many tasks over time. The threads are reused — the same thread object handles multiple tasks sequentially.
If Thread-1 handles Task-A and sets a ThreadLocal value, and Task-A completes without calling .remove(), then:
- Thread-1 goes back to the pool.
- Thread-1 picks up Task-B.
- Task-B calls
threadLocal.get(). - It gets Task-A's leftover value — a bug!
1Thread Pool (5 threads)2
3 Thread-1 → runs Task-1 → sets threadLocal = "data from task 1"4 Task-1 completes. Thread-1 returns to pool.5 ↓ (no cleanup!)6 Thread-1 → runs Task-4 → calls threadLocal.get()7 → GETS "data from task 1" ← BUG! Stale data from a previous task!Code Example Demonstrating the Bug
1import java.util.concurrent.ExecutorService;2import java.util.concurrent.Executors;3
4public class ThreadLocalLeakDemo {5
6 static ThreadLocal<String> threadLocal = new ThreadLocal<>();7
8 public static void main(String[] args) throws InterruptedException {9 ExecutorService pool = Executors.newFixedThreadPool(5);10
11 // Submit one initial task that sets ThreadLocal12 pool.submit(() -> {13 threadLocal.set("TASK_DATA_" + Thread.currentThread().getName());14 System.out.println("Initial task set: " + threadLocal.get());15 // ❌ NO threadLocal.remove() here — intentional to show the bug16 });17
18 Thread.sleep(500); // Let the initial task finish19
20 // Submit 15 more tasks — some threads may be reused21 for (int i = 0; i < 15; i++) {22 pool.submit(() -> {23 // Should be null for fresh use, but might not be!24 System.out.println(Thread.currentThread().getName()25 + " sees: " + threadLocal.get());26 });27 }28
29 pool.shutdown();30 }31}◆ Output (Example non-deterministic)
1pool-1-thread-1 set: TASK_DATA_pool-1-thread-12pool-1-thread-1 sees: TASK_DATA_pool-1-thread-1 ← stale value!3pool-1-thread-2 sees: null4pool-1-thread-3 sees: null5pool-1-thread-1 sees: TASK_DATA_pool-1-thread-1 ← stale again!6...threadLocal.remove(), threads in a pool carry stale data from previous tasks. This can cause data leaks, incorrect behavior, and security vulnerabilities (e.g., one user's session data leaking to another user's request in a web server).Code Example Correct Approach With Cleanup
1import java.util.concurrent.ExecutorService;2import java.util.concurrent.Executors;3
4public class ThreadLocalCleanupDemo {5
6 static ThreadLocal<String> threadLocal = new ThreadLocal<>();7
8 public static void main(String[] args) throws InterruptedException {9 ExecutorService pool = Executors.newFixedThreadPool(5);10
11 // Initial task — sets ThreadLocal AND cleans up12 pool.submit(() -> {13 try {14 threadLocal.set("TASK_DATA_" + Thread.currentThread().getName());15 System.out.println("Initial task set: " + threadLocal.get());16 // ... do work ...17 } finally {18 threadLocal.remove(); // ✅ Always clean up in finally block19 }20 });21
22 Thread.sleep(500);23
24 // 15 subsequent tasks — all should see null25 for (int i = 0; i < 15; i++) {26 pool.submit(() -> {27 System.out.println(Thread.currentThread().getName()28 + " sees: " + threadLocal.get());29 });30 }31
32 pool.shutdown();33 }34}◆ Output
1pool-1-thread-1 set: TASK_DATA_pool-1-thread-12pool-1-thread-1 sees: null3pool-1-thread-2 sees: null4pool-1-thread-3 sees: null5...6(all 15 tasks see null — correct!)threadLocal.remove() inside a finally block so cleanup happens even if an exception is thrown. This is the professional standard.Flowchart Thread Pool Reuse With and Without Cleanup
Key Observations
- You need only one
ThreadLocalobject for all threads — Java automatically routesset()/get()/remove()to the correct thread's storage. - The stored type can be any Java type —
String,Integer,Connection, custom objects — becauseThreadLocalis generic. ThreadLocalprovides thread isolation without locks — there is no synchronization needed because each thread accesses only its own data.- The
ThreadLocalobject is the key inside each thread'sThreadLocalMap. The map is stored inside theThreadobject itself.
Common Mistakes
Mistake 1 Forgetting to Remove in Thread Pools
1// ❌ WRONG2pool.submit(() -> {3 threadLocal.set("value");4 doWork();5 // Forgot to call threadLocal.remove()!6});1// ✅ CORRECT2pool.submit(() -> {3 try {4 threadLocal.set("value");5 doWork();6 } finally {7 threadLocal.remove();8 }9});Mistake 2 Creating One `ThreadLocal` Per Thread
1// ❌ WRONG — unnecessary; defeats the purpose2Thread t1 = new Thread(() -> {3 ThreadLocal<String> local = new ThreadLocal<>(); // Don't create inside thread!4 local.set("value");5});1// ✅ CORRECT — one shared ThreadLocal object2static ThreadLocal<String> local = new ThreadLocal<>();3
4Thread t1 = new Thread(() -> {5 local.set("value"); // Thread-specific, but uses shared object6});Best Practices
- Declare
ThreadLocalasstatic— it should be a class-level constant, not an instance variable. - Always call
.remove()in afinallyblock when using thread pools. - Prefer
ThreadLocalwithinitialValue()override orThreadLocal.withInitial()to provide a default value. - Document usage —
ThreadLocalvariables can be subtle; comment why they exist and when cleanup happens. - Avoid in long-lived threads without cleanup — memory leaks can occur if the thread lives longer than the stored objects.
1// Using withInitial for a default value2ThreadLocal<List<String>> listHolder = ThreadLocal.withInitial(ArrayList::new);Interview Notes
Common Interview Questions on `ThreadLocal`:
- What is
ThreadLocalin Java? — A class that gives each thread its own copy of a variable. - How does
ThreadLocalwork internally? — EachThreadobject holds aThreadLocalMap; theThreadLocalinstance is the key. - Why must you call
threadLocal.remove()in thread pools? — Threads are reused; without removal, stale data from a previous task is visible. - Is
ThreadLocalthread-safe? — Yes, by design — each thread only ever touches its own copy. - When would you use
ThreadLocalover passing parameters? — When the data needs to be accessible across many method calls without being in the method signature (e.g., request context, user session, database connections). - What is
InheritableThreadLocal? — A subclass where child threads inherit the parent thread'sThreadLocalvalues (for propagating context like logging IDs).
Summary
ThreadLocallets each thread store its own private copy of a variable.- One
ThreadLocalobject is shared; the values are separate per thread. - Internally, each
Threadhas aThreadLocalMap— theThreadLocalobject is the key. set()andget()automatically operate on the currently running thread.- Always call
remove()when reusing threads (thread pools) to prevent stale data bugs.
Virtual Threads vs Platform (Normal) Threads
Overview
Virtual Threads are a feature introduced in Java to dramatically improve the scalability of multi-threaded applications. They are a fundamentally different kind of thread — lightweight, managed by the JVM rather than the OS — and they allow applications to handle far more concurrent tasks than traditional threads allow.
Why This Concept Exists
The Problem with Platform Threads
Traditional Java threads (platform threads) have two significant disadvantages:
- Thread creation is expensive — creating a thread involves a system call to the OS, which takes time (milliseconds). This is why
ThreadPoolExecutorwas introduced — to pre-create a pool of threads and reuse them.
- Blocked threads waste OS resources — each platform thread is 1:1 mapped to an OS thread. When a platform thread waits for I/O (database query, network call, file read), the underlying OS thread sits idle — it cannot be used for anything else. OS threads are a limited and expensive resource.
The Goal of Virtual Threads
Virtual Threads solve these problems by:
- Making thread creation nearly free (they are just JVM-level objects).
- Automatically unmounting a virtual thread from its OS thread when it blocks, freeing the OS thread to run other work.
This allows a server to handle millions of concurrent requests with a fraction of the OS resources.
Definition
Platform Thread
(Normal Thread): A Java thread that is a direct 1:1 wrapper around an OS thread. Created and managed by the JVM in cooperation with the operating system. Every platform thread corresponds to exactly one OS thread.
Virtual Thread
: A lightweight, JVM-managed thread that is not tied 1:1 to an OS thread. Many virtual threads can be multiplexed (scheduled) onto a small pool of OS threads (called carrier threads). When a virtual thread blocks, it is unmounted from its carrier thread, freeing that carrier thread to run another virtual thread.
Real-World Analogy
Platform threads are like taxicabs: one cab (OS thread) carries one passenger (task) at a time. If the passenger stops at a shop (I/O wait), the cab sits outside doing nothing — it cannot take another fare.
Virtual threads are like a busy restaurant server: one server (OS thread) can juggle many tables (virtual threads). If one table is waiting for their food (I/O), the server moves on to take other orders — returning when that table's order is ready.
Platform (Normal) Thread Deep Dive
How Platform Threads Work
1Java Code JVM Operating System2──────────────── ────────────────── ──────────────────3new Thread(...) → Creates wrapper → Requests new OS Thread4t.start() → System Call → OS allocates OS Thread5 OS schedules OS Thread6 CPU executes OS Thread- The JVM is just a mediator — a thin wrapper over OS threads.
- 1 Platform Thread = 1 OS Thread (1:1 mapping)
- Creating 10 platform threads = creating 10 OS threads via system calls.
Disadvantages of Platform Threads
◆ Disadvantage 1 Expensive to Create
Calling t.start() triggers a system call (a request from user space to kernel space). System calls are expensive operations that switch execution contexts and involve the OS kernel. This cost (several milliseconds per thread) is why thread pools exist — to amortize this creation cost by reusing threads.
◆ Disadvantage 2 Blocking Wastes OS Resources
1Platform Thread T1 ←→ OS Thread (1:1)2T1 sends DB query3DB takes 4 seconds to respond4↓5OS Thread is BLOCKED for 4 seconds6Cannot do anything else74 seconds of wasted OS thread capacityOS threads are limited. A typical JVM server can support thousands of OS threads before the system runs out of memory (each OS thread requires its own stack, usually 512KB–1MB). If each thread spends most of its time waiting for I/O, most of your OS thread capacity is wasted.
Virtual Thread Deep Dive
How Virtual Threads Work
1Virtual Threads (JVM objects — can be millions)2VT1, VT2, VT3, VT4, ... VT10000003
4 Scheduler (JVM ForkJoinPool)5 ↓ ↓6 OS Thread 1 OS Thread 2 (small pool, e.g., one per CPU core)- Virtual threads are JVM objects — heap-allocated, lightweight, cheap to create.
- The JVM has a small pool of carrier threads (OS threads — usually one per CPU core).
- The JVM scheduler mounts virtual threads onto carrier threads for execution.
- When a virtual thread performs a blocking operation (I/O, sleep), the JVM:
- Unmounts the virtual thread from its carrier thread.
- Saves the virtual thread's state (stack, program counter) on the heap.
- Mounts another runnable virtual thread onto the carrier thread.
- When the blocked operation completes, the original virtual thread is put back in the scheduler queue.
1VT1 mounted on OS-Thread-1 → VT1 calls DB query (blocks)2JVM: unmount VT1 from OS-Thread-1, save VT1's state to heap3JVM: mount VT2 onto OS-Thread-1 → VT2 runs4... DB query response arrives ...5JVM: put VT1 back in scheduler queue6JVM: VT1 mounts on OS-Thread-1 (or OS-Thread-2) when available → resumesKey Result
- OS threads are never idle waiting for I/O.
- You can create millions of virtual threads (they are just objects on the heap).
- Higher throughput: more tasks completed per second using the same hardware.
Availability
--enable-preview for JDK 19/20; no flag needed in JDK 21+.Comparison Table Platform Thread vs Virtual Thread
| Feature | Platform Thread | Virtual Thread |
|---|---|---|
| Mapping | 1:1 with OS Thread | Many:Few with OS Threads |
| Managed by | JVM + OS | JVM (ForkJoinPool scheduler) |
| Creation cost | Expensive (system call) | Cheap (heap object) |
| Memory per thread | 512KB–1MB (OS stack) | Small (heap, grows dynamically) |
| Max practical count | ~Thousands | ~Millions |
| Blocking behavior | Blocks OS thread | OS thread freed; VT parked on heap |
| Throughput | Lower | Higher |
| Latency | Same | Same (not designed to improve latency) |
| Backward compatible | — | Yes — all Thread APIs work |
| Introduced | JDK 1.0 | JDK 19 (preview), JDK 21 (GA) |
| Also called | Normal thread, OS thread | Lightweight thread, green thread (conceptually) |
Throughput vs Latency Why Virtual Threads Improve Throughput Only
- If your DB query takes 4 seconds, a virtual thread still waits 4 seconds for the result — latency is unchanged.
- But while that virtual thread waits, the OS thread handles other virtual threads — so your server processes more requests in total per second.
- Throughput = tasks per second. Virtual threads significantly increase this.
- Latency = time for one request. Virtual threads do not reduce this.
Diagrams
Platform Thread Model
Virtual Thread Model
Virtual Thread Lifecycle During Blocking I/O
Syntax Creating Virtual Threads
Method 1 `Thread.ofVirtual()`
1// Create and start a virtual thread with a Runnable2Thread vt = Thread.ofVirtual().start(() -> {3 System.out.println("Running in virtual thread: "4 + Thread.currentThread().isVirtual());5});6vt.join();Method 2 `Executors.newVirtualThreadPerTaskExecutor()`
1import java.util.concurrent.ExecutorService;2import java.util.concurrent.Executors;3
4try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {5 executor.submit(() -> {6 System.out.println("Task running in: "7 + Thread.currentThread().getName()8 + " | isVirtual: " + Thread.currentThread().isVirtual());9 });10} // auto-closes and awaits completionSyntax Breakdown
| Syntax | Explanation |
|---|---|
Thread.ofVirtual() | Returns a Thread.Builder configured to create virtual threads |
.start(Runnable) | Creates and immediately starts the virtual thread |
Executors.newVirtualThreadPerTaskExecutor() | Creates an ExecutorService that spawns a new virtual thread for each submitted task |
executor.submit(Runnable) | Submits a task — each task gets its own virtual thread |
Thread.currentThread().isVirtual() | Returns true if the current thread is a virtual thread |
try-with-resources on ExecutorService | Automatically shuts down and awaits task completion (JDK 19+) |
Code Examples
Example 1 Basic Virtual Thread
1public class VirtualThreadBasic {2 public static void main(String[] args) throws InterruptedException {3
4 // Create and start a virtual thread5 Thread vt = Thread.ofVirtual().start(() -> {6 System.out.println("Thread name: " + Thread.currentThread().getName());7 System.out.println("Is virtual: " + Thread.currentThread().isVirtual());8 });9
10 vt.join(); // Wait for it to finish11 }12}◆ Output
1Thread name: 2Is virtual: true.name("myVT").Example 2 Creating Many Virtual Threads (Power Demo)
1import java.util.ArrayList;2import java.util.List;3
4public class ManyVirtualThreads {5 public static void main(String[] args) throws InterruptedException {6 List<Thread> threads = new ArrayList<>();7
8 // Create 100,000 virtual threads — would be impossible with platform threads9 for (int i = 0; i < 100_000; i++) {10 Thread vt = Thread.ofVirtual().start(() -> {11 try {12 Thread.sleep(1000); // Simulate I/O wait13 } catch (InterruptedException e) {14 Thread.currentThread().interrupt();15 }16 });17 threads.add(vt);18 }19
20 // Wait for all to complete21 for (Thread t : threads) {22 t.join();23 }24
25 System.out.println("All 100,000 virtual threads completed.");26 }27}◆ Output
1All 100,000 virtual threads completed.OutOfMemoryError or crash the OS. Virtual threads handle this gracefully because they are heap objects.Example 3 Using `newVirtualThreadPerTaskExecutor`
1import java.util.concurrent.ExecutorService;2import java.util.concurrent.Executors;3
4public class VirtualThreadExecutor {5 public static void main(String[] args) {6
7 try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {8 for (int i = 1; i <= 10; i++) {9 final int taskId = i;10 executor.submit(() -> {11 System.out.println("Task " + taskId12 + " | Thread: " + Thread.currentThread().getName()13 + " | Virtual: " + Thread.currentThread().isVirtual());14 });15 }16 } // Executor shuts down here; all tasks complete before this line exits17 }18}◆ Output (order may vary)
1Task 1 | Thread: | Virtual: true2Task 3 | Thread: | Virtual: true3Task 2 | Thread: | Virtual: true4...5Task 10 | Thread: | Virtual: trueExample 4 Platform Thread vs Virtual Thread Comparison
1import java.util.concurrent.ExecutorService;2import java.util.concurrent.Executors;3
4public class ThroughputComparison {5
6 static void simulateIOTask(String label) {7 try {8 Thread.sleep(100); // Simulate 100ms I/O (DB, network, etc.)9 } catch (InterruptedException e) {10 Thread.currentThread().interrupt();11 }12 }13
14 public static void main(String[] args) throws InterruptedException {15 int taskCount = 1000;16
17 // --- Platform Thread Pool (fixed 10 threads) ---18 long start1 = System.currentTimeMillis();19 try (ExecutorService platformPool = Executors.newFixedThreadPool(10)) {20 for (int i = 0; i < taskCount; i++) {21 platformPool.submit(() -> simulateIOTask("platform"));22 }23 }24 long end1 = System.currentTimeMillis();25 System.out.println("Platform threads (10 threads): " + (end1 - start1) + "ms");26
27 // --- Virtual Threads ---28 long start2 = System.currentTimeMillis();29 try (ExecutorService virtualPool = Executors.newVirtualThreadPerTaskExecutor()) {30 for (int i = 0; i < taskCount; i++) {31 virtualPool.submit(() -> simulateIOTask("virtual"));32 }33 }34 long end2 = System.currentTimeMillis();35 System.out.println("Virtual threads (1 per task): " + (end2 - start2) + "ms");36 }37}◆ Output (approximate)
1Platform threads (10 threads): ~10000ms2Virtual threads (1 per task): ~200msExplanation: With 10 platform threads and 1000 tasks (each taking 100ms), tasks run in batches of 10 → ~100 batches → ~10 seconds. With virtual threads, all 1000 run concurrently → ~100ms. This demonstrates the throughput advantage.
Memory and JVM Behavior
Platform Thread Memory
1OS Memory2┌──────────────────────────────────┐3│ OS Thread Stack: 512KB–1MB each │ ← fixed, allocated by OS4│ Thread Metadata │5└──────────────────────────────────┘- Each platform thread requires ~512KB–1MB of OS memory for its stack.
- 10,000 platform threads = ~5–10 GB of memory just for stacks.
Virtual Thread Memory
1JVM Heap2┌──────────────────────────────────────────┐3│ Virtual Thread Object: small (~few KB) │ ← grows on demand4│ Stack (stored on heap when parked) │5│ Grows and shrinks dynamically │6└──────────────────────────────────────────┘- Virtual thread stacks start tiny and grow dynamically on the heap.
- When parked (blocked), the stack state is saved to the heap; the carrier thread is freed.
- Much lower memory footprint per thread.
Backward Compatibility
All the following work identically with virtual threads:
synchronizedblocks and methodsReentrantLock,ReadWriteLockwait(),notify(),notifyAll()Thread.sleep()ExecutorServicesubmissionsFuture,CompletableFutureThreadLocal(works, but with caveats — see below)
The only difference is how the JVM manages scheduling — the developer-facing API is unchanged.
`ThreadLocal` with Virtual Threads
ThreadLocal works with virtual threads, be cautious. Since virtual threads are designed to be created in large numbers (millions), using ThreadLocal to store heavy objects per virtual thread can cause memory pressure. Prefer scoped values (ScopedValue, JDK 21+) for virtual thread context propagation.Key Observations
- Virtual threads are not faster than platform threads for CPU-bound tasks. They shine for I/O-bound workloads.
- One virtual thread per task is the recommended pattern — no need to tune pool sizes.
- JVM controls the carrier thread pool size (typically one per CPU core) — developers cannot configure this directly.
- Pinning is a known limitation: if a virtual thread executes inside a
synchronizedblock and blocks on I/O, it may stay pinned to its carrier thread (this is being improved in newer JDK versions). - No need for thread pools with virtual threads for most use cases — just create a virtual thread per task.
Common Mistakes
Mistake 1 Using Virtual Threads for CPU-Bound Work
1// ❌ No benefit — CPU-bound tasks don't block on I/O2try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {3 executor.submit(() -> {4 long sum = 0;5 for (long i = 0; i < 1_000_000_000L; i++) sum += i; // pure CPU6 return sum;7 });8}9// Virtual threads don't help here; use ForkJoinPool or platform threads for CPU workMistake 2 Limiting Virtual Threads with a Fixed Pool
1// ❌ Defeats the purpose — wrapping virtual threads in a fixed pool2ExecutorService limited = Executors.newFixedThreadPool(100); // wrong for virtual threads1// ✅ CORRECT — let the JVM create virtual threads per task freely2try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {3 // submit tasks4}Mistake 3 Using `synchronized` with Long Blocking in Virtual Threads (Pinning)
1// ⚠️ May cause pinning — VT stays bound to carrier thread during blocking I/O inside synchronized2synchronized (lock) {3 slowDatabaseCall(); // Blocks inside synchronized → potential pinning4}5// Use ReentrantLock instead for better virtual thread compatibility:6lock.lock();7try { slowDatabaseCall(); } finally { lock.unlock(); }Best Practices
- Use virtual threads for I/O-bound tasks — database calls, HTTP requests, file reads/writes.
- Use
newVirtualThreadPerTaskExecutor()as your default executor for I/O-heavy workloads. - Do not pool virtual threads — unlike platform threads, they are cheap to create; create one per task.
- Prefer
ReentrantLockoversynchronizedinside virtual threads for better interoperability. - Monitor pinning with JVM flags:
-Djdk.tracePinnedThreads=fullto detect if virtual threads are stuck to carrier threads. - Continue using platform threads for CPU-intensive work (number crunching, compression, etc.).
Interview Notes
Commonly Asked Interview Questions on Virtual Threads:
- What is a virtual thread in Java? — A lightweight, JVM-managed thread not tied 1:1 to an OS thread, designed for high-throughput I/O-bound applications.
- What is the difference between virtual threads and platform threads? — Platform threads have 1:1 mapping to OS threads; virtual threads are multiplexed on a small carrier thread pool by the JVM.
- Why were virtual threads introduced? — To achieve higher throughput in I/O-bound applications without the overhead of OS thread creation and management.
- Do virtual threads improve latency? — No. They improve throughput (tasks per second), not the time taken for one individual task.
- What is a carrier thread? — An OS thread that virtual threads are mounted onto for execution.
- What is pinning in virtual threads? — When a virtual thread cannot be unmounted from its carrier thread (e.g., while inside a
synchronizedblock), blocking the carrier thread. - Can you use
ThreadLocalwith virtual threads? — Yes, but it's not recommended for heavy objects at scale. UseScopedValue(JDK 21) instead. - In which JDK version were virtual threads released? — Preview in JDK 19, GA (generally available) in JDK 21.
- What is the recommended executor for virtual threads? —
Executors.newVirtualThreadPerTaskExecutor().
Mind Map
Summary
`ThreadLocal`
| Point | Detail |
|---|---|
| Purpose | Give each thread its own isolated copy of a variable |
| Key mechanism | Each Thread has a ThreadLocalMap; the ThreadLocal object is the key |
| API | set(T), get(), remove() |
| Automatic routing | Operations always apply to the currently running thread |
| Critical rule | Always call remove() when reusing threads in a thread pool |
| Type | Generic — can store any type |
Virtual Threads vs Platform Threads
| Point | Platform Thread | Virtual Thread |
|---|---|---|
| Mapping to OS | 1:1 | Many:Few |
| Creation cost | High (system call) | Low (heap object) |
| Scale | Thousands | Millions |
| Blocking behavior | OS thread blocked | OS thread freed, VT parked |
| Goal | General-purpose | Higher throughput for I/O |
| Availability | Since JDK 1.0 | JDK 21 (GA) |
| API | new Thread(...) | Thread.ofVirtual(), newVirtualThreadPerTaskExecutor() |
ThreadLocal → per-thread data, always .remove() in pools.
- Virtual Threads → high throughput, I/O-bound, cheap, JDK 21+, backward compatible.
- Platform Threads → 1:1 OS, expensive, limited scale, good for CPU-bound.End of Chapter — Java Advanced Multithreading: ThreadLocal & Virtual Threads
Mastery check
How well can you recall this?
Finished this lesson?