Java Core13 interview questions
Virtual Threads and Project Loom in Java 21
How virtual threads change the threading model, when to use them, carrier thread pinning pitfalls, and migration patterns for Spring Boot applications.
Java 21Virtual ThreadsLoomConcurrency
Virtual Threads and Project Loom in Java 21
What Are Virtual Threads?
Virtual threads are lightweight threads managed by the JVM, not the OS. They are cheap to create and block — you can have millions of them.
java
// Platform thread (expensive)
Thread t = new Thread(runnable);
// Virtual thread (cheap)
Thread vt = Thread.ofVirtual().start(runnable);
// Via ExecutorService
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> handleRequest(request));
}Spring Boot 3.2+ Integration
yaml
spring:
threads:
virtual:
enabled: trueThis switches Tomcat's thread pool to use virtual threads automatically.
Carrier Thread Pinning
Virtual threads are mounted on OS (carrier) threads. Pinning occurs when a virtual thread cannot be unmounted:
- 1.synchronized blocks: Use ReentrantLock instead
- 2.Native method calls: Cannot be avoided
java
// PINNING - blocks carrier thread
synchronized(lock) {
Thread.sleep(1000); // carrier is pinned!
}
// NON-PINNING
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
Thread.sleep(1000); // carrier is free
} finally {
lock.unlock();
}Interview Questions
- 1.How are virtual threads scheduled onto carrier threads?
- 2.What is the difference between virtual threads and async/reactive?
- 3.When should you NOT use virtual threads?
- 4.How do you detect carrier thread pinning in production?
- 5.Do virtual threads improve CPU-bound or I/O-bound workloads?