Video in progress
What is virtual thread "pinning", and what problem does it cause in Java 21?
Pinning is when a virtual thread blocks and can't come off its carrier thread, so it keeps the carrier occupied. In Java 21 this happens when it blocks inside a synchronized block or a native method; since there are few carriers, the whole application can grind to a halt.
📖 Answer
Normally, when a virtual thread waits for I/O, it "unmounts" from the carrier. But in Java 21 the monitor is tied to the carrier thread, so:
synchronized (this) {
var resp = httpClient.send(request, ofString()); // the carrier stays occupied
}
By default the number of carriers equals the number of cores. On an 8-core server, if 8 virtual threads wait in a block like this, the thousands of other virtual threads can't find anywhere to run. From the outside it looks like a deadlock: the CPU is idle and there is no response.
How to find it:
-Djdk.tracePinnedThreads=fullprints a stack trace when pinning happens (Java 21–23);- the
jdk.VirtualThreadPinnedevent in JFR.
Solutions on Java 21:
- in places with long waits, use
ReentrantLockinstead ofsynchronized; - a
synchronizedthat protects short, in-memory operations is not a problem, since it finishes quickly; - update your libraries: many JDBC drivers and HTTP clients replaced their internal locks for this reason.
In Java 24 (JEP 491), synchronized no longer pins. Native code and some rare cases still pin. So if you stay on Java 21 LTS, you definitely need to check this.
Sign up to mark studied questions and save your progress.