← Back to Advanced Java Course | Chapter 2: Multithreading | Lesson 8 of 8

Java में Thread Pools

एक thread pool workers की एक ऐसी team है जो कई jobs के लिए reuse की जाती है, जैसे किराये का इंतज़ार कर रहे taxi drivers का एक समूह। यह हर बार एक नया worker hire करने से तेज़ है।
Syntax
java
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

java
// 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();
	}
}

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

java
// 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();
	}
}

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

java
// 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();
	}
}

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

java
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();
	}
}

Shutting Down Thread Pools

आपके बनाए thread pools को ज़रूरत न रहने पर हमेशा shut down करें, क्योंकि उनके live worker threads अन्यथा JVM को चलता रखेंगे और resources को अनिश्चित काल तक leak करेंगे। पहले से चल रहे tasks को सुचारू रूप से खत्म होने देने के लिए shutdown() का उपयोग करें, या तुरंत रोकने के लिए shutdownNow() का उपयोग करें।

उदाहरण: Shutting Down Thread Pools

java
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
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. कई लंबे tasks से भर देते हुए newCachedThreadPool() का उपयोग करना, क्योंकि यह हर एक के लिए एक नया thread बनाता है और memory खत्म कर सकता है।
  2. किसी pool पर shutdown() call न करना, जिससे इसके threads जीवित रहते हैं और program कभी खत्म नहीं होता।
  3. scheduleAtFixedRate से किसी repeating task को schedule करना जो एक uncaught exception फेंकता है, जो चुपचाप उसके बाद के सभी runs को cancel कर देता है; task के अंदर exceptions catch करें।
चैप्टर सारांश
  • Threads किसी program को एक साथ कई चीज़ें करने देते हैं, और वे states के एक lifecycle से गुज़रते हैं।
  • Runnable, synchronization, और wait तथा notify threads को सुरक्षित रूप से एक साथ काम करने में मदद करते हैं।
  • Executors, Callable, Future, और thread pools threads और उनके results को manage करते हैं।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.