Java में Thread Pools
In this page:
ExecutorService pool = Executors.newFixedThreadPool(poolSize);
pool.execute(runnable);
pool.shutdown();
Introduction to Thread Pools
हर task के लिए बिल्कुल नया thread बनाना असली memory और scheduling overhead जोड़ता है, और load के तहत बार-बार ऐसा करना किसी application की performance को घटा सकता है और उसे अस्थिर भी कर सकता है। एक thread pool इसे हल करता है reusable worker threads की एक queue बनाए रखकर जिन्हें tasks सौंपे जाते हैं, मांग पर fresh threads spawn करने के बजाय।
उदाहरण: Introduction to Thread Pools
// Import java.util.concurrent.ExecutorService so it can be used by its short name
import java.util.concurrent.ExecutorService;
// Import java.util.concurrent.Executors so it can be used by its short name
import java.util.concurrent.Executors;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Create a thread pool to run tasks
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(() -> System.out.println("Reused worker thread runs this task"));
pool.shutdown();
}
}
Login to try C/C++/Java/PHP code in the editor
Cached Thread Pools
एक cached thread pool current load के आधार पर खुद को dynamically resize करता है: यह नए threads बनाता है जब tasks मौजूदा threads के process कर पाने से तेज़ आते हैं, और यह उन threads को retire कर देता है जो कुछ समय से idle बैठे हैं। यह इसे कई short-lived, bursty tasks वाले workloads के लिए अच्छी तरह उपयुक्त बनाता है।
उदाहरण: Cached Thread Pools
// Import java.util.concurrent.ExecutorService so it can be used by its short name
import java.util.concurrent.ExecutorService;
// Import java.util.concurrent.Executors so it can be used by its short name
import java.util.concurrent.Executors;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Create a thread pool to run tasks
ExecutorService pool = Executors.newCachedThreadPool();
// Loop: repeat while the condition holds
for (int i = 0; i < 3; i++) {
pool.submit(() -> System.out.println("Short-lived task"));
}
pool.shutdown();
}
}
Login to try C/C++/Java/PHP code in the editor
Scheduled Thread Pools
एक scheduled thread pool आपको tasks को किसी निर्धारित delay के बाद एक बार चलने के लिए, या किसी fixed rate या fixed interval पर बार-बार चलने के लिए schedule करने देता है, बिना खुद timers manage किए। यह periodic cache refreshes या health checks जैसे background jobs के लिए standard building block है।
उदाहरण: Scheduled Thread Pools
// Import java.util.concurrent.* so it can be used by its short name
import java.util.concurrent.*;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) throws InterruptedException {
// Create a thread pool to run tasks
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(() -> System.out.println("Ran after delay"), 100, TimeUnit.MILLISECONDS);
Thread.sleep(200);
scheduler.shutdown();
}
}
Login to try C/C++/Java/PHP code in the editor
Single Thread Executor
एक single-thread executor pool हर submitted task को एक dedicated background thread पर क्रमवार चलाता है, यह गारंटी देते हुए कि tasks बिल्कुल उसी order में execute होंगे जिसमें उन्हें submit किया गया था। यह तब उपयोगी है जब आपको explicit locking की जटिलता के लिए भुगतान किए बिना predictable, race-free ordering चाहिए।
उदाहरण: Single Thread Executor
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.submit(() -> System.out.println("First"));
pool.submit(() -> System.out.println("Second")); // guaranteed to run after First
pool.shutdown();
}
}
Login to try C/C++/Java/PHP code in the editor
Shutting Down Thread Pools
आपके बनाए thread pools को ज़रूरत न रहने पर हमेशा shut down करें, क्योंकि उनके live worker threads अन्यथा JVM को चलता रखेंगे और resources को अनिश्चित काल तक leak करेंगे। पहले से चल रहे tasks को सुचारू रूप से खत्म होने देने के लिए shutdown() का उपयोग करें, या तुरंत रोकने के लिए shutdownNow() का उपयोग करें।
उदाहरण: Shutting Down Thread Pools
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(() -> System.out.println("Task"));
pool.shutdown(); // lets running tasks finish
// pool.shutdownNow(); // would force an immediate stop instead
}
}
Login to try C/C++/Java/PHP code in the editor
- कई लंबे tasks से भर देते हुए
newCachedThreadPool()का उपयोग करना, क्योंकि यह हर एक के लिए एक नया thread बनाता है और memory खत्म कर सकता है। - किसी pool पर
shutdown()call न करना, जिससे इसके threads जीवित रहते हैं और program कभी खत्म नहीं होता। scheduleAtFixedRateसे किसी repeating task को schedule करना जो एक uncaught exception फेंकता है, जो चुपचाप उसके बाद के सभी runs को cancel कर देता है; task के अंदर exceptions catch करें।
- Threads किसी program को एक साथ कई चीज़ें करने देते हैं, और वे states के एक lifecycle से गुज़रते हैं।
Runnable, synchronization, औरwaitतथाnotifythreads को सुरक्षित रूप से एक साथ काम करने में मदद करते हैं।- Executors,
Callable,Future, और thread pools threads और उनके results को manage करते हैं।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: