J.VI · Java 25 practice question

A developer is migrating a traditional blocking I/O service from platform threads to use virtual threads in Java 25. They observe that while the application feels more responsive under load, CPU-intensive, long-running calculations initiated within the virtual thread still seem to consume disproportionate resources compared to the expected lightweight nature of virtual threads. What is the correct pattern or understanding to ensure that CPU-bound tasks, which do not naturally release the underlying carrier thread, are handled efficiently without blocking the thread pool unnecessarily?

// Example conceptual setup
try {
    Thread.startVirtualThread(() -> {
        // CPU-intensive loop calculation
        for (long i = 0; i < 1_000_000_000L; i++) {
            Math.sqrt((double) i);
        }
    });
} catch (Exception e) {
    // handle
}
Choose one answer
Check answer and explanation

Correct answer: For truly CPU-bound tasks, the developer should explicitly use platform threads or `ForkJoinPool` because virtual threads only provide benefits for blocking I/O operations.

Explanation

Virtual threads are optimized for I/O-bound tasks where threads spend most of their time waiting (blocking). When a task is purely CPU-bound, it runs continuously and monopolizes the underlying carrier thread until it completes. If the goal is to limit parallel execution of CPU-intensive work, traditional thread pool management (like `ForkJoinPool` or fixed thread pools) is the appropriate pattern, as virtual threads do not inherently provide CPU throttling mechanisms; they only manage scheduling when waiting.

Common trap

Options A and B misunderstand the fundamental purpose and limitation of virtual threads. Option D is a good general practice, but Option C directly addresses the *nature* of the task (CPU-bound) versus the tool (virtual thread), explaining why a different execution model is superior for that specific bottleneck.

Source: Java SE Documentation - Thread class (https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Thread.html)
Checked against the cited text on 2026-11-27.

Report an error in this question