Java / Java 21 Coding Standards Interview Questions
Explain the lifecycle of a virtual thread under Java 21 coding standard recommendations?
A virtual thread is created via Thread.ofVirtual() or Executors.newVirtualThreadPerTaskExecutor(), and it moves through the same conceptual states as a platform thread - new, runnable, running, waiting or blocked, and terminated - but the JVM, not the OS, schedules it onto a small pool of carrier (platform) threads.
flowchart LR
A[New] --> B[Runnable]
B --> C[Running on a carrier thread]
C -->|blocking call e.g. I/O| D[Unmounted / Waiting]
D -->|carrier thread freed for other virtual threads| B
C --> E[Terminated]
The key difference from a platform thread's lifecycle is the unmount step: when a virtual thread performs a blocking operation such as I/O or waiting on a lock, the JVM detaches it from its carrier thread, which is then free to run a different virtual thread, and the original virtual thread is re-mounted onto some carrier once its blocking operation completes.
Coding standards recommend against pooling virtual threads or reusing them across tasks - unlike platform threads, they are meant to be created fresh per task and allowed to terminate naturally, since their creation cost is intentionally low enough to make pooling unnecessary and even counterproductive.
More Related questions...