बैच प्रोसेसिंग के लिए थ्रेड पूल लागू करना
मान लीजिए आप एक डॉक्यूमेंट प्रोसेसिंग सिस्टम बना रहे हैं जिसे एक साथ कई डॉक्यूमेंट संभालने हैं। हर डॉक्यूमेंट में भारी प्रोसेसिंग लगती है जो parallel होनी चाहिए, लेकिन सिस्टम ओवरलोड से बचने के लिए आप concurrent ऑपरेशनों की संख्या सीमित रखना चाहते हैं। आप ExecutorService का इस्तेमाल करके ऐसा समाधान लागू करेंगे जो प्रोसेसिंग वर्कलोड को कुशलता से मैनेज करे।
यह अभ्यास पाठ्यक्रम का हिस्सा है
Java में कोड ऑप्टिमाइज़ करना
अभ्यास निर्देश
- 3 थ्रेड्स वाला एक fixed thread pool बनाएँ.
processDocument(doc)मेथड को एक टास्क के रूप में एक्जीक्यूटर को सबमिट करें.- एक्जीक्यूटर को बिना तुरंत forcefully terminate किए shutdown करें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
public class DocumentProcessor {
public static void main(String[] args) throws InterruptedException {
List documents = List.of("Doc1", "Doc2", "Doc3", "Doc4", "Doc5");
List> futures = new ArrayList<>();
// Create a fixed thread pool with 3 threads
ExecutorService executor = Executors.____(____);
for (String doc : documents) {
// Submit the processDocument() method to the executor
futures.add(executor.submit(() -> ____(____)));
}
// Shutdown the executor and wait for termination
executor.____();
executor.awaitTermination(10, TimeUnit.SECONDS);
try {
for (Future future : futures) {
System.out.println(future.get());
}
} catch (ExecutionException e) {
System.out.println("Error processing documents: " + e.getMessage());
}
}
private static String processDocument(String docId) throws InterruptedException {
System.out.println("Processing " + docId + " on thread " + Thread.currentThread().getName());
Thread.sleep((long) (Math.random() * 1000));
return docId + " Processed";
}
}