Video in progress
When moving to Java 21 virtual threads, what do you pay attention to in the Hibernate and JDBC layer?
Virtual threads don't make the database faster: the real limit is still the connection pool. Blocking I/O inside synchronized can pin the carrier thread (before Java 24), so I check driver and pool versions and treat the pool as a semaphore.
📖 Answer
Virtual threads remove the cost of platform threads for tasks that mostly wait. But a Hibernate query still takes a JDBC connection, and Hikari has, say, 20 of them. 10,000 virtual threads arrive and queue up for 20 connections. Throughput does not increase; the queue just moves from the Tomcat thread pool to Hikari.
The decisions that follow:
Connection wait time. Keep connection-timeout short, otherwise thousands of virtual threads wait 30 seconds and then all fail at once. Sometimes it is better to put an explicit Semaphore in front of the pool and reject excess requests quickly.
Pinning. On Java 21-23, if a virtual thread blocks inside a synchronized block, it holds the carrier thread. Older JDBC drivers and pools had a lot of synchronized inside. PostgreSQL JDBC 42.6+ and newer Hikari versions have moved to ReentrantLock in many places. On Java 24 (JEP 491) this problem is mostly solved. To check: -Djdk.tracePinnedThreads=full (Java 21-23) or the jdk.VirtualThreadPinned event in JFR.
ThreadLocal. Hibernate itself does not bind the Session to the thread, but Spring's transaction synchronization uses ThreadLocal, and it works correctly with virtual threads because each request has its own thread. The problem is only code that keeps a big cache in a ThreadLocal: now there can be millions of copies.
spring:
threads:
virtual:
enabled: true
datasource:
hikari:
maximum-pool-size: 20
connection-timeout: 1000
My takeaway: for a CRUD service that talks to a database, virtual threads are often neutral. The benefit shows up in services with a lot of slow I/O outside the database (external HTTP).
Sign up to mark studied questions and save your progress.