Java / Java 21 Virtual Threads Interview questions
What happens when you call Thread.sleep() inside a virtual thread?
Thread.sleep() has been adapted so that, when called from a virtual thread, it doesn't tie up the carrier thread for the sleep duration.
Thread.startVirtualThread(() -> { Thread.sleep(Duration.ofSeconds(5)); // carrier is freed during this wait System.out.println("woke up"); });
Instead, the virtual thread is unmounted and a timer schedules it to become runnable again once the sleep interval elapses, at which point the scheduler assigns it to whichever carrier is available. On a platform thread, by contrast, sleep() blocks the underlying OS thread for the full duration.
More Related questions...