पाठ 11 / 39

Virtual Threads (Java 21)

हल्के virtual threads से भारी concurrency संभालें जो blocking code को सस्ता बनाते हैं, और जानें कि platform threads कब फिट बैठते हैं।

सस्ते threads

Virtual thread को OS नहीं बल्कि JVM schedule करता है, इसलिए लाखों चलाए जा सकते हैं। जब कोई I/O पर block हो तो JVM उसे park करता है और carrier thread दोबारा उपयोग करता है। इससे सरल thread-per-request शैली scalable रहती है।

Virtual threads बनाना

Thread.ofVirtual() या ऐसा executor उपयोग करें जो हर task के लिए एक virtual thread शुरू करे।

Thread.ofVirtual().name("worker-1").start(() -> fetch(url));

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (String u : urls) {
        executor.submit(() -> fetch(u));   // one cheap thread per task
    }
}   // close() waits for all tasks

Virtual threads I/O-bound काम में मदद करते हैं, CPU-bound loops में नहीं। उन्हें pool न करें, blocking calls के आसपास लंबे synchronized blocks से बचें और ReentrantLock उपयोग करें।

त्वरित जाँच

त्वरित जाँच: Virtual threads किसके लिए सबसे उपयुक्त हैं?

  • Many concurrent blocking I/O tasks
  • CPU-bound number crunching only
  • Replacing the garbage collector
  • Compiling code
Answer

Many concurrent blocking I/O tasks — वे blocking I/O को सस्ता बनाते हैं ताकि thread-per-task code scale हो सके।