Quick revision
The short answer
Each virtual thread has its own ThreadLocal values, and with one virtual thread per request there is one thread per concurrent request instead of a fixed pool of 200. So the per-thread cache turns into one 1 MB buffer per in-flight request: 5,000 concurrent requests hold about 5 GB, and every buffer is allocated once and used once. ThreadLocal as an object cache assumes few, long-lived threads, which virtual threads break. We replace it with a bounded object pool, smaller or streaming buffers, or plain allocation per use, and confirm the change with heap histograms before and after.
What to remember
In this answer, we saw that a per-thread 1 MB buffer was bounded and reused on a 200-thread pool, but with one virtual thread per request every request allocates its own buffer and never reuses it, so memory grows with concurrency. The pattern assumes few, long-lived threads, which virtual threads break. We replaced it with a bounded pool, streaming or right-sized allocation, and confirmed the change with class histograms and GC metrics before and after.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Each virtual thread has its own ThreadLocal values, and with one virtual thread per request there is one thread per concurrent request instead of a fixed pool of 200. So the per-thread cache turns into one 1 MB buffer per in-flight request: 5,000 concurrent requests hold about 5 GB, and every buffer is allocated once and used once. ThreadLocal as an object cache assumes few, long-lived threads, which virtual threads break. We replace it with a bounded object pool, smaller or streaming buffers, or plain allocation per use, and confirm the change with heap histograms before and after.
Why this question is asked
Caching expensive objects in a ThreadLocal was a standard optimisation for years, and many libraries still do it. Turning on virtual threads is often a single configuration switch, so these caches are rarely noticed until memory alerts fire. Interviewers ask this question because it tests whether we understand the assumption hidden inside the optimisation, not just the API. In this answer, we will recap why the cache made sense on a platform thread pool, show what changes with virtual threads with real numbers, explain the broken assumption, go through three replacements and finish with how to measure the result.
1Why the Cache Made Sense on a Thread Pool
The service serialises JSON into a 1 MB byte buffer. Allocating 1 MB for every request is not free: large arrays may be allocated directly in the old generation, and frequent large allocations increase garbage collection work. So someone cached one buffer per thread.
On a Tomcat pool of 200 platform threads, this is at most 200 buffers, 200 MB, allocated once and reused for millions of requests. The memory is fixed and bounded by the pool size, which is why the trick worked.
2What Changes With Virtual Threads
A virtual thread is a real java.lang.Thread, so it has its own ThreadLocal map exactly like a platform thread. With Spring Boot's spring.threads.virtual.enabled or Tomcat's virtual thread executor, each request gets a brand new virtual thread, which ends when the request ends. There is no pool of reused threads anymore.
So the first BUFFER.get() on every request finds no value, runs the initializer and allocates a fresh 1 MB array. The cache never hits. While the request is running, its buffer is reachable from its thread, and when the thread ends, the buffer becomes garbage. The number of live buffers equals the number of concurrent requests, which virtual threads are designed to make large.
| Thread model | Threads | Live 1 MB buffers | Reuse |
|---|---|---|---|
| Platform pool of 200 | 200, reused | 200 (200 MB) | Millions of hits per buffer |
| Virtual, 500 concurrent requests | 500, one per request | 500 (500 MB) | None: one use each |
| Virtual, 5,000 concurrent requests | 5,000, one per request | 5,000 (about 5 GB) | None: one use each |
3The Assumption Virtual Threads Break
A ThreadLocal used as an object cache silently assumes two things: that there are few threads, so the number of copies is small, and that threads live long, so each copy is reused many times. Platform thread pools satisfy both. Virtual threads deliberately violate both: they are cheap so we create one per task, and short-lived because the task is their whole life. The JDK documentation for virtual threads warns about exactly this pattern.
Notice that the code has no bug in the usual sense. It is correct, it just costs memory proportional to concurrency with no benefit, and it adds GC pressure from millions of large short-lived arrays. ThreadLocals used for request context, such as a tenant id, are fine on virtual threads, because they are small and are meant to live for one request. It is the caching use that breaks.
4Fix 1: A Bounded Pool of Buffers
If allocation of the buffer really is expensive, we share a fixed number of them among all threads with a bounded pool. The bound is now explicit and independent of the thread count.
Memory held by the pool is at most 64 MB. Under bursts, extra buffers are allocated and dropped, so the cost degrades gracefully rather than failing. The catch is that pooling adds code and a risk of using a buffer after returning it, so we use it only when measurements say allocation is the real cost.
5Fix 2: Smaller Buffers or Plain Allocation
Often the better fix is to question the buffer. Most responses are far smaller than 1 MB, so writing into a ByteArrayOutputStream that starts at 8 KB and grows, or streaming directly to the response output stream, allocates only what the response needs. Jackson can write straight to an OutputStream, which removes the large buffer altogether.
Modern garbage collectors handle short-lived small objects very cheaply, since they die young and are collected in bulk. So plain allocation per use, sized to the data, is usually faster overall than a cache, and it is certainly simpler.
6Measuring Before and After
We confirm both the diagnosis and the fix with data. A class histogram, taken with jcmd <pid> GC.class_histogram, lists live objects by class, and a large count of byte[] instances near 1 MB each points straight at the cache. A heap dump analysed in a tool such as Eclipse MAT shows that the arrays are reachable from VirtualThread objects through their ThreadLocal maps. After the fix, we compare the same histogram under the same load, along with GC metrics such as allocation rate and pause times, and the process memory at peak concurrency.
It is also worth searching dependencies for the same pattern, since some libraries cache buffers or encoders in ThreadLocals, and checking their release notes for virtual-thread-friendly versions.
7Follow-up questions
Can we keep the ThreadLocal if we limit the number of virtual threads?
Limiting concurrency with a semaphore limits the live buffers, but the cache still never hits, because every request runs on a new thread. We would keep all the cost of allocation and none of the benefit. Limiting is useful for protecting downstream resources, not for saving this cache.
Are ThreadLocals for request context safe with virtual threads?
Yes. A small value such as a trace id or tenant id that lives for one request is exactly what a per-thread value is for, and the cost is tiny. Scoped values, final in Java 25, are a better fit for new code, because they bind a value for a scope and remove it automatically.
What about InheritableThreadLocal and virtual threads?
Virtual threads inherit inheritable values from their creator by default, which copies references at creation for every new thread. For large values that can add memory and surprises, so we keep inherited values small or switch them off for that builder.
8Conclusion
In this answer, we saw that a per-thread 1 MB buffer was bounded and reused on a 200-thread pool, but with one virtual thread per request every request allocates its own buffer and never reuses it, so memory grows with concurrency. The pattern assumes few, long-lived threads, which virtual threads break. We replaced it with a bounded pool, streaming or right-sized allocation, and confirmed the change with class histograms and GC metrics before and after.
Open with
The ThreadLocal cache only works because of an assumption: few threads that live a long time. On a Tomcat pool of 200 platform threads you get 200 buffers, 200 megabytes, reused millions of times.
Then, if they want more
A virtual thread is a real Thread with its own ThreadLocal map, and with virtual threads enabled each request gets a new thread that ends with the request. So every request misses the cache, allocates a fresh one megabyte buffer, uses it once and drops it, and the number of live buffers equals the number of concurrent requests.
At five thousand concurrent requests that's about five gigabytes, plus a lot of GC pressure from large short-lived arrays. Nothing is incorrect in the code; the optimisation just turned into its opposite.
To fix it, I'd first question the buffer: most responses are much smaller, so I'd stream with Jackson straight to the output stream, or allocate a right-sized buffer per use and let the GC handle it, which modern collectors do very cheaply.
If measurement shows allocation really is the cost, I'd use a bounded pool, say 64 buffers in an ArrayBlockingQueue, with a fallback allocation when it's empty, so memory is capped independently of thread count. I'd confirm with jcmd GC.class_histogram before and after under the same load, look at the allocation rate, and check our dependencies for the same pattern.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 25
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A JSON service caches a 1 MB byte buffer per thread in a ThreadLocal to avoid...": https://scrivio-interview-library.netlify.app/java/threads/0de02de857/