ChatGPT,OpenAI开发的文本生成AI聊天机器人,自2022年11月推出以来席卷全球。最初作为通过简短文本提示来提升写作论文和代码生产力的工具...
2025-08-17 0
Java 21 引入的结构化并发(Structured Concurrency)是对传统并发编程模型的重大改进。它通过明确的任务生命周期管理和作用域控制,解决了长期以来困扰开发者的线程泄漏、任务状态难以追踪等问题。结构化并发的核心目标是:
作用域是结构化并发的核心概念,用于管理一组任务的生命周期。通过 Scope 接口,开发者可以:
import java.util.concurrent.ExecutionException;import java.util.concurrent.Scope;import java.util.concurrent.StructuredTaskScope;public class ScopeExample { public static void main(String[] args) throws InterruptedException { try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { var task1 = scope.fork(() -> { System.out.println("Task 1 started"); Thread.sleep(1000); System.out.println("Task 1 completed"); return "Result 1"; }); var task2 = scope.fork(() -> { System.out.println("Task 2 started"); Thread.sleep(2000); System.out.println("Task 2 completed"); return "Result 2"; }); scope.join(); System.out.println("Both tasks completed"); System.out.println("Task 1 result: " + task1.resultNow()); System.out.println("Task 2 result: " + task2.resultNow()); } }}
任务句柄代表异步执行的任务,提供了以下功能:
import java.util.concurrent.ExecutionException;import java.util.concurrent.StructuredTaskScope;public class TaskHandleExample { public static void main(String[] args) throws InterruptedException { try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { var parentTask = scope.fork(() -> { var childTask = scope.fork(() -> { System.out.println("Child task started"); Thread.sleep(1000); System.out.println("Child task completed"); return "Child result"; }); System.out.println("Parent task waiting for child"); return childTask.resultNow(); }); scope.join(); System.out.println("Parent task result: " + parentTask.resultNow()); } }}
结构化并发提供了多种异常处理模式:
import java.util.concurrent.StructuredTaskScope;public class ExceptionHandlingExample { public static void main(String[] args) throws InterruptedException { // ShutdownOnFailure 模式 try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { scope.fork(() -> { throw new RuntimeException("Task 1 failed"); }); scope.fork(() -> { System.out.println("Task 2 started"); return "Result 2"; }); scope.join(); } catch (Exception e) { System.out.println("Caught exception: " + e.getMessage()); } // ContinueOnFailure 模式 try (var scope = new StructuredTaskScope.ContinueOnFailure()) { scope.fork(() -> { throw new RuntimeException("Task A failed"); }); scope.fork(() -> { throw new RuntimeException("Task B failed"); }); scope.join(); System.out.println("All exceptions: " + scope.exceptions()); } }}
import java.util.concurrent.StructuredTaskScope;public class TaskDependencyExample { public static void main(String[] args) throws InterruptedException { try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { var task1 = scope.fork(() -> { System.out.println("Task 1 started"); Thread.sleep(1000); return "Result 1"; }); var task2 = scope.fork(() -> { System.out.println("Task 2 started"); Thread.sleep(2000); return "Result 2"; }); var task3 = scope.fork(() -> { System.out.println("Task 3 started"); System.out.println("Task 1 result: " + task1.resultNow()); System.out.println("Task 2 result: " + task2.resultNow()); return "Result 3"; }); scope.join(); System.out.println("Task 3 result: " + task3.resultNow()); } }}
import java.io.Closeable;import java.util.concurrent.StructuredTaskScope;public class ResourceManagementExample { public static void main(String[] args) throws InterruptedException { try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { var resource = new DatabaseConnection(); scope.fork(() -> { try { resource.query("SELECT * FROM users"); } finally { resource.close(); } }); scope.join(); } } static class DatabaseConnection implements Closeable { public void query(String sql) { System.out.println("Executing query: " + sql); } @Override public void close() { System.out.println("Closing database connection"); } }}
import java.time.Duration;import java.util.concurrent.StructuredTaskScope;public class TimeoutExample { public static void main(String[] args) throws InterruptedException { try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { var task = scope.fork(() -> { System.out.println("Task started"); Thread.sleep(3000); System.out.println("Task completed"); return "Result"; }); scope.join(Duration.ofSeconds(2)); if (task.isDone()) { System.out.println("Task result: " + task.resultNow()); } else { System.out.println("Task timed out"); task.cancel(); } } }}
结构化并发通过以下方式提升性能:
import java.util.concurrent.Executors;import java.util.concurrent.StructuredTaskScope;public class VirtualThreadIntegrationExample { public static void main(String[] args) throws InterruptedException { try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { var executor = Executors.newVirtualThreadPerTaskExecutor(); for (int i = 0; i < 10000; i++) { scope.fork(() -> { executor.submit(() -> { System.out.println("Virtual thread task"); return "Result"; }); return null; }); } scope.join(); } }}
结构化并发需要 JDK 21 或更高版本支持。在低版本中,可以通过以下方式模拟部分功能:
未来可能引入新的字节码指令,直接支持结构化并发的生命周期管理。
结构化并发是 Java 并发编程的重大突破,通过明确的任务生命周期管理和作用域控制,显著提升了代码的安全性和可维护性。在实际开发中,结构化并发适用于以下场景:
尽管结构化并发需要 JDK 21 及以上版本支持,但它已经展现出巨大的潜力。随着 Java 生态的持续优化,结构化并发将成为现代 Java 开发的标准实践。合理使用结构化并发,能够有效减少并发编程中的错误,提高系统的可靠性和性能。
相关文章
ChatGPT,OpenAI开发的文本生成AI聊天机器人,自2022年11月推出以来席卷全球。最初作为通过简短文本提示来提升写作论文和代码生产力的工具...
2025-08-17 0
上个月,OPPO Find系列产品负责人周意保发文确认,今年下半年发布Find X9、Find X9 Pro等新机,明年上半年发布Find X9s、F...
2025-08-17 0
来源:【新黄河】新黄河记者:黄敏 8月17日,2025世界人形机器人运动会迎来最后一天比赛。济南企业山东优宝特智能机器人有限公司(以下简称“优宝特”)...
2025-08-17 0
一、结构化并发的核心概念与设计目标Java 21 引入的结构化并发(Structured Concurrency)是对传统并发编程模型的重大改进。它通...
2025-08-17 1
如今,像 GPT 系列这样的大模型已经展现出了惊人的通用能力,但要让它们在某个具体领域发挥最大效力,还需要进行“微调”(Fine-Tuning)。传统...
2025-08-17 1
8月17日下午,2025世界人形机器人运动会完成所有赛项,圆满落幕。闭幕式上,所有获得冠军的队伍并肩登台亮相。此次赛事中,各冠军队伍的表现不仅展现了人...
2025-08-17 0
8月17日下午,2025世界人形机器人运动会赛场,在5V5足球决赛中,清华大学火神队力克强队德国队,斩获含金量十足的冠军。在这一全新的顶级赛场上夺冠,...
2025-08-17 1
今天带来:小身材大能量——微星 MPG B850I EDGE TI WIFI 刀锋钛主板开箱简测。这是微星 MSI 专为 AMD 锐龙 9000 桌面...
2025-08-17 1
发表评论