java / expert
Snippet
Virtual Thread Pinning and ReentrantLock
Virtual threads can be 'pinned' to their carrier platform thread if they block inside a 'synchronized' block or call native methods. To maintain high throughput and scalability, developers should replace 'synchronized' with 'ReentrantLock', which allows the virtual thread to unmount correctly.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
private final ReentrantLock lock = new ReentrantLock();public void safeExecution() {lock.lock();try {// Blocking I/O or long taskexternalService.call();} finally {lock.unlock();}}
Breakdown
1
private final ReentrantLock lock = new ReentrantLock();
Using ReentrantLock instead of synchronized to prevent pinning.
2
lock.lock(); ... lock.unlock();
Ensures the virtual thread can be suspended by the scheduler while waiting for the lock.