← Back to Advanced Java Course | Chapter 4: Modern Java Features | Lesson 10 of 12

Java में Structured Concurrency

Structured Concurrency संबंधित concurrent subtasks के एक group को shared lifetime वाली एक single unit की तरह treat करता है, fork, join, और errors को predictably propagate करने के लिए StructuredTaskScope का उपयोग करते हुए।
Syntax
java
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
    var task = scope.fork(() -> work());
    scope.join();
    scope.throwIfFailed();
    task.get();
}

What is Structured Concurrency?

Structured concurrency, जिसे virtual threads के साथ preview किया गया, संबंधित concurrent subtasks के एक group को एक single unit की तरह treat करता है जो साथ शुरू और खत्म होता है, ad-hoc thread management को एक scope से replace करते हुए जिसकी एक साफ़, predictable lifetime है।

उदाहरण: What is Structured Concurrency?

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Print a line to the console
		System.out.println("Related subtasks start and finish together as one unit");
	}
}

StructuredTaskScope Basics

एक StructuredTaskScope try-with-resources block में खोला जाता है, और इसका fork method अपनी खुद की virtual thread पर एक subtask शुरू करता है, जबकि join तब तक block करता है जब तक उस scope का हर forked subtask पूरा न हो जाए।

उदाहरण: StructuredTaskScope Basics

java
import java.util.concurrent.StructuredTaskScope;
public class Main {
	public static void main(String[] args) throws Exception {
		try (var scope = new StructuredTaskScope<String>()) {
			scope.fork(() -> "subtask result"); // runs on its own virtual thread
			scope.join(); // blocks until every forked subtask completes
			System.out.println("All subtasks finished");
		}
	}
}

Forking Subtasks

कई संबंधित subtasks, जैसे एक ही response के लिए ज़रूरी data के अलग-अलग हिस्सों को fetch करना, एक scope के अंदर fork किए जा सकते हैं ताकि वे concurrently चलें, और हर एक बाद में उसका result निकालने के लिए एक Subtask handle return करता है।

उदाहरण: Forking Subtasks

java
import java.util.concurrent.StructuredTaskScope;
public class Main {
	public static void main(String[] args) throws Exception {
		try (var scope = new StructuredTaskScope<Integer>()) {
			var task1 = scope.fork(() -> 10);
			var task2 = scope.fork(() -> 20); // both run concurrently
			scope.join();
			System.out.println(task1.get() + task2.get());
		}
	}
}

Joining and Handling Results

join के return होने के बाद, हर subtask का outcome उपलब्ध होता है: get() एक सफल result निकालता है, और ShutdownOnSuccess जैसे specialized scopes पहले subtask के सफल होते ही पूरे operation को खत्म होने देते हैं, बाकी को cancel करते हुए।

उदाहरण: Joining and Handling Results

java
import java.util.concurrent.StructuredTaskScope;
public class Main {
	public static void main(String[] args) throws Exception {
		try (var scope = new StructuredTaskScope.ShutdownOnSuccess<Integer>()) {
			scope.fork(() -> 1);
			scope.fork(() -> 2);
			scope.join();
			System.out.println("First success: " + scope.result()); // finishes on first success, cancels the rest
		}
	}
}

Error Propagation

ShutdownOnFailure किसी भी एक subtask के fail होते ही scope के हर दूसरे subtask को cancel कर देता है, और throwIfFailed उस failure को उस thread पर फिर से raise करता है जो scope का मालिक है, concurrent subtasks में structured, predictable error handling देते हुए।

उदाहरण: Error Propagation

java
import java.util.concurrent.StructuredTaskScope;
public class Main {
	public static void main(String[] args) throws Exception {
		try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
			scope.fork(() -> { throw new RuntimeException("subtask failed"); });
			scope.join();
			scope.throwIfFailed(); // re-raises the failure on the owning thread
		} catch (Exception e) {
			System.out.println("Caught: " + e.getCause().getMessage());
		}
	}
}
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. scope.join() से पहले किसी subtask का get() call करना, जो IllegalStateException फेंकता है क्योंकि results अभी तैयार नहीं हैं।
  2. यह भूल जाना कि कई Java versions में StructuredTaskScope एक preview API है, इसलिए code को compile और run करने के लिए --enable-preview चाहिए।
  3. किसी fail हुए subtask पर get() call करना, जो throw करता है, बजाय state() जांचने या throwIfFailed() उपयोग करने के।

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.