Quick revision
The short answer
Every virtual thread has its own id, and the virtual-thread executor creates a new thread for every task, so a cache keyed by Thread.currentThread().getId() gets a new key for every request. The library assumed a few long-lived pooled threads, so it expected about 200 entries; now it opens a new connection per task, never reuses one, and usually never closes them. The fix is to replace the per-thread cache with a proper connection pool, and to audit other code that uses thread identity or ThreadLocal as a cache.
What to remember
In this answer, we saw that a library caching connections by Thread.currentThread().getId() relied on threads being few and long-lived, which a pool guaranteed. Virtual threads create a new thread with a new id for every task, so the cache gains an entry per request, connections are never reused and never closed, and the database fills up. The fix is a real connection pool, which lends connections per call and also limits concurrency, and an audit of other code that uses thread identity or ThreadLocal as a cache.
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.
Every virtual thread has its own id, and the virtual-thread executor creates a new thread for every task, so a cache keyed by Thread.currentThread().getId() gets a new key for every request. The library assumed a few long-lived pooled threads, so it expected about 200 entries; now it opens a new connection per task, never reuses one, and usually never closes them. The fix is to replace the per-thread cache with a proper connection pool, and to audit other code that uses thread identity or ThreadLocal as a cache.
Why this question is asked
This bug looks mysterious at first: the code has not changed, it worked for years, and suddenly the database reports thousands of open connections. It is one of the most common migration problems with virtual threads, and the same pattern hides in many libraries in less obvious forms. Interviewers ask it to see whether we can reason from how virtual threads are created to why an old assumption breaks. In this answer, we will reproduce the library's behaviour, see why it was fine with a thread pool, explain what changes with virtual threads, then fix it and look at how to find similar code.
1What the Library Does
The library wants to avoid opening a connection for every call, so it keeps one connection per thread in a map keyed by the thread's id. The idea is that each thread reuses its own connection and no two threads ever share one, so no locking is needed.
Notice what is missing: nothing ever removes an entry or closes a connection. With a pool of threads, that was acceptable, because the same threads were reused for the whole life of the application.
2Why It Worked With a Thread Pool
With platform threads, Tomcat used a pool of about 200 threads, created once and reused for every request. Thread ids stayed the same, so the map grew to about 200 entries during warm-up and then stopped growing. Each request ran on one of those 200 threads, looked up its id, and reused that thread's connection. The library effectively had a pool of 200 connections, sized by accident by the thread pool, and the database saw a steady 200 connections per instance.
3What Changes With Virtual Threads
With virtual threads, there is no pool. Executors.newVirtualThreadPerTaskExecutor(), and Tomcat with virtual threads enabled, create a brand-new thread for every task. Each new thread gets a new, unique id. So every request calls connection() from a thread whose id has never been seen, computeIfAbsent finds no entry, and a new connection is opened.
The consequences pile up. Connections are never reused, because no thread id ever comes back. They are never closed, because the map holds them forever even after the thread has ended, so they leak both on our side, as map entries that the garbage collector cannot free, and on the database side, as open sessions. After 10,000 requests there are 10,000 connections, or until the database refuses more with an error such as too many connections. The map is also a memory leak: each finished virtual thread leaves its connection behind.
| Aspect | Pool of 200 platform threads | Virtual thread per task |
|---|---|---|
| Distinct thread ids | 200, reused forever | one new id per task |
| Map entries after 1 hour | 200 | one per request served |
| Connections reused | yes, by the same thread | never |
| Connections closed | at shutdown | never, they leak |
| Database sessions | steady at 200 | grow until the database refuses |
4The Fix: Use a Real Connection Pool
The library really wanted a pool of connections, and it built one out of thread identity. The fix is to use an actual pool, which hands out connections for the duration of a call and takes them back afterwards, independent of which thread asks. For JDBC, that is a DataSource backed by HikariCP, which Spring Boot configures by default; for other protocols, the client's own pooling.
Notice two things that changed. The connection is borrowed for one call and returned in try-with-resources, so the number of connections depends on how many calls are in progress, not on how many threads have ever existed. And the pool has a maximum, 30 here, so it also acts as the concurrency limit for the database that the old thread pool used to provide by accident. With virtual threads, many requests may wait for one of those 30 connections; the connection timeout makes that wait bounded. If the library itself cannot be changed, upgrading it, or wrapping it so calls go through a pool, is the next best option.
5Audit Other Uses of Thread Identity and ThreadLocal
The same assumption, that threads are few and long-lived, hides in other forms, and it is worth searching for them before the next incident. Any map keyed by thread id or by the Thread object itself has the same leak. A ThreadLocal used as a cache, such as a per-thread buffer, parser or client, does not leak the same way, because thread-local values are released when the thread ends, but it stops caching anything: every task creates the expensive object again, and with 20,000 concurrent requests there are 20,000 copies alive at once.
A practical audit searches the code and dependencies for getId(), threadId(), Thread as a map key, and ThreadLocal fields whose values are expensive or hold resources. Each finding is then classified: context passing, which is fine and can later move to scoped values, cheap values, which are fine, and caches of expensive or resource-holding objects, which should become shared pools or immutable shared instances. Load testing with virtual threads enabled while watching database sessions, open file descriptors and heap is the safety net for anything the search misses.
- Search for getId, threadId, Thread keys, ThreadLocalown code and libraries
- Does it cache an expensive object or a resource?connection, client, large bufferYesReplace with a shared pool or immutable instanceNoContinue
- Is it context passed down a call?request id, userYesKeep; consider scoped values laterNoLeave as is
- Load test with virtual threads onwatch sessions, file descriptors, heap
4 steps in order. Play them, or step through them one at a time.
6Follow-up questions
Why is getId() deprecated?
Since Java 19, Thread.getId() is deprecated in favour of threadId(), because getId() is not final and a subclass could override it, so the returned value was not guaranteed to identify the thread. threadId() is final. Both return the same unique id; the deprecation does not change the bug.
Would a WeakHashMap keyed by Thread fix the leak?
It would let entries disappear after their threads are garbage collected, but the connections would still not be closed properly, and every task would still open a new one. It treats a symptom; a real pool solves the problem.
Why did nobody notice in testing?
Tests often run a handful of requests, so a handful of connections is normal. The problem only shows under sustained load with many distinct tasks, which is why a load test with virtual threads enabled, watching database sessions, should be part of every migration.
7Conclusion
In this answer, we saw that a library caching connections by Thread.currentThread().getId() relied on threads being few and long-lived, which a pool guaranteed. Virtual threads create a new thread with a new id for every task, so the cache gains an entry per request, connections are never reused and never closed, and the database fills up. The fix is a real connection pool, which lends connections per call and also limits concurrency, and an audit of other code that uses thread identity or ThreadLocal as a cache.
Open with
The library assumed threads are few and long-lived. It keeps a map from thread id to connection, so each thread reuses its own connection. With a Tomcat pool of 200 threads that worked by accident: 200 ids, 200 map entries, 200 connections, reused forever.
Then, if they want more
With virtual threads, there's no pool. Every task, so every request, runs on a brand-new virtual thread with a brand-new id, so computeIfAbsent never finds an entry and opens a new connection each time.
Those connections are never reused, because no id comes back, and never closed, because the map holds them forever, so you leak map entries on our side and sessions on the database side until it refuses connections. The fix is to stop using thread identity as a pool and use a real connection pool, like HikariCP behind a DataSource.
Connections are borrowed per call in try-with-resources and returned, and the pool's maximum size, say 30, becomes the explicit concurrency limit for the database that the thread pool used to give us implicitly, with a connection timeout so waits are bounded.
Then I'd audit for the same assumption elsewhere: maps keyed by thread or thread id, and ThreadLocals that cache expensive objects or resources, which stop caching and multiply with concurrency. And I'd load test with virtual threads on, watching database sessions and file descriptors.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 19
- 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
- JEP 444, Virtual Threads
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 "After moving to virtual threads, a library that used Thread.currentThread().getId() as a...": https://scrivio-interview-library.netlify.app/java/virtual-threads/3f6a61a5b3/