Java / Java 21 Virtual Threads Interview questions
How do you troubleshoot thread pinning caused by synchronized blocks?
Start by making pinning visible. The JVM can print a stack trace every time a virtual thread pins its carrier by launching with a diagnostic flag:
java -Djdk.tracePinnedThreads=full -jar myapp.jar
Use short instead of full for a more compact trace. You can also capture the jdk.VirtualThreadPinned Java Flight Recorder event for a lower-overhead, production-friendly way to see when and where pinning happens over time.
Once you've located the offending synchronized block, check whether it also performs a blocking call inside it. If so, replace the monitor with a java.util.concurrent.locks.ReentrantLock, or restructure the code so the blocking call happens outside the critical section entirely. Re-run the trace afterward to confirm the pinning event no longer fires.
More Related questions...