Java / Java 21 Virtual Threads Interview questions
What is the difference between synchronized blocks and ReentrantLock for pinning?
In Java 21, when a virtual thread blocks while holding a monitor acquired through a synchronized block or method, it stays pinned to its carrier thread - the JVM can't unmount it mid-monitor-hold, so the carrier is stuck idle for that duration.
// Pins the carrier if lock1.lock() blocks inside synchronized (lock1) { blockingCall(); } // Does NOT pin: uses java.util.concurrent locking instead reentrantLock.lock(); try { blockingCall(); } finally { reentrantLock.unlock(); }
java.util.concurrent.locks.ReentrantLock doesn't rely on the JVM's built-in monitor mechanism, so a virtual thread waiting on it, or blocking while holding it, can still be unmounted normally, keeping the carrier thread free.
More Related questions...