JDK27结构化并发

0 阅读1分钟

前言

随着JDK27发布,结构化并发也有新的语法,JDK 27 结构化并发(StructuredTaskScope,预览特性 JEP 533) 的演示:并行跑两个任务,并可以设置超时

JDK27结构化并发

import java.util.concurrent.*;
import java.time.Duration;

public class StructuredDemo {
    static void main() throws Exception {
        // 默认快速失败策略 + 2秒超时
        try (var scope = StructuredTaskScope.open(
                cfg -> cfg.withTimeout(Duration.ofSeconds(2)))) {

            StructuredTaskScope.Subtask<String> task1 = scope.fork(() -> {
                Thread.sleep(5000);
                return "Result A";
            });

            StructuredTaskScope.Subtask<String> task2 = scope.fork(() -> {
                Thread.sleep(300);
                return "Result B";
            });

            scope.join();

            System.out.println(task1.get() + " | " + task2.get());
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

输出结果为

image.png

import java.util.concurrent.*;
import java.time.Duration;

public class StructuredDemo {
    static void main() throws Exception {
        // 默认快速失败策略 + 2秒超时
        try (var scope = StructuredTaskScope.open(
                cfg -> cfg.withTimeout(Duration.ofSeconds(2)))) {

            StructuredTaskScope.Subtask<String> task1 = scope.fork(() -> {
                Thread.sleep(1000);
                return "Result A";
            });

            StructuredTaskScope.Subtask<String> task2 = scope.fork(() -> {
                Thread.sleep(300);
                return "Result B";
            });

            scope.join();

            System.out.println(task1.get() + " | " + task2.get());
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

输出结果为

image.png

总结

结构化并发可以设置超时时长,但是目前在JDK27还属于预览属性,需要开启预览特性