Java 21 LTS虚拟线程
2026/1/15大约 4 分钟JavaJava版本特性LTS虚拟线程JavaJava新特性LambdaStreamOptional模块化
概述
Java 21(2023年9月)是第四个 LTS 版本,虚拟线程正式发布,这是 Java 并发编程的重大革新。
虚拟线程 (正式)
虚拟线程是轻量级线程,由 JVM 管理,可以创建数百万个而不会耗尽系统资源。
创建虚拟线程
// 方式1:Thread.ofVirtual()
Thread vThread = Thread.ofVirtual().start(() -> {
System.out.println("Hello from virtual thread!");
});
// 方式2:Thread.startVirtualThread()
Thread vThread2 = Thread.startVirtualThread(() -> {
System.out.println("Another virtual thread");
});
// 方式3:使用工厂
ThreadFactory factory = Thread.ofVirtual().factory();
Thread t = factory.newThread(() -> doWork());
t.start();
// 方式4:ExecutorService
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> task1());
executor.submit(() -> task2());
}虚拟线程 vs 平台线程
// 平台线程 - 受系统资源限制
// 通常只能创建几千个
try (var executor = Executors.newFixedThreadPool(200)) {
for (int i = 0; i < 10000; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return "done";
});
}
}
// 虚拟线程 - 可以创建数百万个
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1_000_000; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return "done";
});
}
}虚拟线程特性
// 检查是否是虚拟线程
Thread.currentThread().isVirtual();
// 虚拟线程命名
Thread.ofVirtual()
.name("worker-", 0) // worker-0, worker-1, ...
.factory();
// 虚拟线程不支持的操作
// - 不能设置优先级(总是 NORM_PRIORITY)
// - 不能设置为守护线程(总是守护线程)
// - 不支持 stop()、suspend()、resume()Record 模式 (正式)
record Point(int x, int y) {}
record Line(Point start, Point end) {}
// 解构 Record
void printSum(Object obj) {
if (obj instanceof Point(int x, int y)) {
System.out.println("Sum: " + (x + y));
}
}
// 嵌套解构
void printLine(Object obj) {
if (obj instanceof Line(Point(int x1, int y1), Point(int x2, int y2))) {
System.out.println("From (" + x1 + "," + y1 + ") to (" + x2 + "," + y2 + ")");
}
}
// 在 switch 中使用
String describe(Object obj) {
return switch (obj) {
case Point(int x, int y) when x == y -> "Diagonal point";
case Point(int x, int y) -> "Point(" + x + ", " + y + ")";
case Line(Point p1, Point p2) -> "Line from " + p1 + " to " + p2;
default -> "Unknown";
};
}Switch 模式匹配 (正式)
// 类型模式
String format(Object obj) {
return switch (obj) {
case Integer i -> "int: " + i;
case Long l -> "long: " + l;
case Double d -> "double: " + d;
case String s -> "String: " + s;
case int[] arr -> "int array of length " + arr.length;
case null -> "null";
default -> obj.toString();
};
}
// 守卫条件
String classify(Integer num) {
return switch (num) {
case Integer i when i < 0 -> "negative";
case Integer i when i == 0 -> "zero";
case Integer i when i > 0 && i < 100 -> "small positive";
case Integer i -> "large positive";
};
}
// 密封类型穷尽
sealed interface Shape permits Circle, Rectangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
double area(Shape shape) {
return switch (shape) {
case Circle(var r) -> Math.PI * r * r;
case Rectangle(var w, var h) -> w * h;
};
}顺序集合 (Sequenced Collections)
新的接口,为有序集合提供统一的 API。
// SequencedCollection
SequencedCollection<String> list = new ArrayList<>();
list.addFirst("first");
list.addLast("last");
String first = list.getFirst();
String last = list.getLast();
list.removeFirst();
list.removeLast();
SequencedCollection<String> reversed = list.reversed();
// SequencedSet
SequencedSet<String> set = new LinkedHashSet<>();
set.addFirst("a");
set.addLast("z");
SequencedSet<String> reversedSet = set.reversed();
// SequencedMap
SequencedMap<String, Integer> map = new LinkedHashMap<>();
map.putFirst("first", 1);
map.putLast("last", 99);
Map.Entry<String, Integer> firstEntry = map.firstEntry();
Map.Entry<String, Integer> lastEntry = map.lastEntry();
SequencedMap<String, Integer> reversedMap = map.reversed();集合层次结构
Collection
├── SequencedCollection
│ ├── List
│ ├── Deque
│ └── SequencedSet
│ ├── SortedSet
│ └── LinkedHashSet
Map
└── SequencedMap
├── SortedMap
└── LinkedHashMap字符串模板 (预览)
// STR 模板处理器
String name = "World";
String message = STR."Hello, \{name}!";
// 表达式
int x = 10, y = 20;
String result = STR."\{x} + \{y} = \{x + y}";
// 多行
String json = STR."""
{
"name": "\{name}",
"value": \{x + y}
}
""";
// FMT 模板处理器(格式化)
double price = 19.99;
String formatted = FMT."Price: %.2f\{price}";
// 自定义模板处理器
StringTemplate.Processor<JSONObject, RuntimeException> JSON =
template -> new JSONObject(template.interpolate());
JSONObject obj = JSON."""
{
"name": "\{name}",
"age": \{age}
}
""";未命名模式和变量 (预览)
// 未命名变量 _
try {
// ...
} catch (Exception _) {
// 不需要使用异常变量
System.out.println("Error occurred");
}
// 在 for 循环中
int count = 0;
for (var _ : list) {
count++;
}
// 在 Lambda 中
map.forEach((_, value) -> System.out.println(value));
// 未命名模式
if (obj instanceof Point(int x, _)) {
// 只关心 x 坐标
System.out.println("x = " + x);
}
// 在 switch 中
switch (obj) {
case Point(int x, _) -> System.out.println("x = " + x);
case Line(_, Point end) -> System.out.println("ends at " + end);
default -> {}
}外部函数和内存 API (第三次预览)
// 调用本地函数
try (Arena arena = Arena.ofConfined()) {
// 分配本地内存
MemorySegment segment = arena.allocate(ValueLayout.JAVA_INT, 10);
// 设置值
for (int i = 0; i < 10; i++) {
segment.setAtIndex(ValueLayout.JAVA_INT, i, i * 2);
}
// 调用 C 函数
Linker linker = Linker.nativeLinker();
SymbolLookup stdlib = linker.defaultLookup();
MethodHandle strlen = linker.downcallHandle(
stdlib.find("strlen").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS)
);
MemorySegment str = arena.allocateUtf8String("Hello");
long len = (long) strlen.invoke(str);
}结构化并发 (预览)
// 同时执行多个任务,统一处理结果
Response handle() throws ExecutionException, InterruptedException {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Subtask<String> user = scope.fork(() -> fetchUser());
Subtask<Integer> order = scope.fork(() -> fetchOrder());
scope.join(); // 等待所有任务完成
scope.throwIfFailed(); // 如果有失败则抛出异常
return new Response(user.get(), order.get());
}
}
// 返回第一个成功的结果
String fetchFirst() throws ExecutionException, InterruptedException {
try (var scope = new StructuredTaskScope.ShutdownOnSuccess<String>()) {
scope.fork(() -> fetchFromSource1());
scope.fork(() -> fetchFromSource2());
scope.join();
return scope.result();
}
}总结
| 特性 | 说明 |
|---|---|
| 虚拟线程 | 正式发布,轻量级并发 |
| Record 模式 | 正式发布,解构 Record |
| Switch 模式匹配 | 正式发布,强大的模式匹配 |
| 顺序集合 | 有序集合的统一 API |
| 字符串模板 | 预览,字符串插值 |
| 未命名模式 | 预览,忽略不需要的变量 |
Java 21 是一个里程碑版本,虚拟线程的正式发布将彻底改变 Java 的并发编程模式,使高并发应用的开发变得更加简单高效。
