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

Java का Executor Framework

Executor Framework एक manager है जो worker threads को jobs सौंपता है, जैसे एक boss जो team को tasks देता है। आप काम submit करते हैं और यह तय करता है कि इसे कौन करेगा।
Syntax
java
ExecutorService executor = Executors.newFixedThreadPool(n);
executor.submit(task);
executor.shutdown();

What is the Executor Framework?

Executor framework Java 5 में introduced एक built-in concurrency library है जो thread pools, task queues, और scheduling को अपने आप manage करती है। यह खुद Thread objects को manually बनाने, शुरू करने, और track करने की ज़रूरत हटा देती है, जो application को एक मुट्ठी से ज़्यादा concurrent tasks चाहिए होने पर error-prone हो जाता है।

उदाहरण: What is the Executor Framework?

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 executor = Executors.newFixedThreadPool(2);
		executor.submit(() -> System.out.println("Task managed by the pool"));
		executor.shutdown();
	}
}

Single Thread Executor

एक Single Thread Executor बिल्कुल एक background worker thread manage करता है और हर submitted task को क्रमवार चलाता है, बिल्कुल उस order में जिसमें वे tasks submit किए गए थे। यह आपको single-threaded execution की सुरक्षा देता है — tasks के बीच कोई race conditions नहीं — जबकि फिर भी उस काम को calling thread से दूर रखता है।

उदाहरण: Single Thread Executor

java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
	public static void main(String[] args) {
		ExecutorService executor = Executors.newSingleThreadExecutor();
		executor.submit(() -> System.out.println("Task 1"));
		executor.submit(() -> System.out.println("Task 2")); // runs after Task 1, same worker
		executor.shutdown();
	}
}

Fixed Thread Pool

एक Fixed Thread Pool worker threads की एक निश्चित संख्या manage करता है और submitted tasks को जो भी thread खाली हो उसे सौंपता है, हर बार एक नया spawn करने के बजाय हर thread को कई tasks में reuse करते हुए। यह resource usage को predictably bound करता है, जो भारी या अचानक load में काफी मायने रखता है।

उदाहरण: Fixed Thread Pool

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 executor = Executors.newFixedThreadPool(3);
		// Loop: repeat while the condition holds
		for (int i = 1; i <= 5; i++) {
			// Declare taskId and set it to i
			int taskId = i;
			executor.submit(() -> System.out.println("Task " + taskId));
		}
		executor.shutdown();
	}
}

Submitting Callable Tasks

Runnable interface के विपरीत, Callable interface उन tasks को represent करता है जो एक computed result return कर सकते हैं और execution के दौरान checked exceptions फेंक सकते हैं। किसी executor को एक Callable submit करने पर आपको वापस एक Future मिलता है जिसका उपयोग आप task खत्म होने पर वह result पाने के लिए कर सकते हैं।

उदाहरण: Submitting Callable Tasks

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 Exception {
		// Create a thread pool to run tasks
		ExecutorService executor = Executors.newSingleThreadExecutor();
		Callable<Integer> task = () -> 10 + 20;
		Future<Integer> future = executor.submit(task);
		// Print a line to the console
		System.out.println(future.get());
		executor.shutdown();
	}
}

Shutting Down Executors

आप जो executors बनाते हैं उन्हें हमेशा explicitly shut down करें, क्योंकि उनके worker threads अन्यथा JVM को हमेशा के लिए जीवित रखेंगे। पहले से submitted कामों को सामान्य रूप से खत्म होने देते हुए नए tasks accept करना बंद करने के लिए shutdown() call करें, या जब सब कुछ तुरंत रोकना हो तो shutdownNow() का उपयोग करें।

उदाहरण: Shutting Down Executors

java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
	public static void main(String[] args) {
		ExecutorService executor = Executors.newFixedThreadPool(2);
		executor.submit(() -> System.out.println("Task running"));
		executor.shutdown(); // stop accepting new tasks, finish existing ones
	}
}
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. executor पर shutdown() call करना भूल जाना, जिससे इसके non-daemon worker threads JVM को exit होने से रोकते हैं।
  2. हर submit के ठीक बाद future.get() call करना, जिससे tasks parallel में चलने के बजाय एक के बाद एक चलते हैं।
  3. किसी Runnable के साथ submit का उपयोग करना जो throw करता है और कभी Future को न जांचना, क्योंकि exception Future में store हो जाता है और चुपचाप खो जाता है।

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.