JDK21新特性
🌟 JDK 21 新特性全解析
Java 21 是继 Java 17 后的又一个 LTS(长期支持)版本,标志着 Java 平台进入了更现代化的阶段。
该版本在语言特性、虚拟机能力、标准 API 以及性能层面进行了多项增强,特别引入了 虚拟线程、结构化并发 等革新性特性,对高并发程序开发产生了深远影响。
✨ 一览:JDK 21 新特性速查表
🔹 1. 虚拟线程(Virtual Threads)
📌 简介
虚拟线程是 Java 为解决传统线程数量瓶颈而引入的新型线程模型,属于 Project Loom 的核心成果。
虚拟线程由 JVM 管理,而非操作系统线程,因此创建成本极低,非常适合 Web 服务、高并发 I/O 等场景。
✅ 优势
每个任务可独立一个线程,无需线程池调度
使用同步阻塞编程模型,开发更简单
高并发性能媲美 Netty、异步框架
✅ 示例代码(带注释)
public class VirtualThreadDemo {
public static void main(String[] args) {
// 启动一个虚拟线程执行任务
Thread.startVirtualThread(() -> {
System.out.println("这是一个虚拟线程:" + Thread.currentThread());
});
// 使用线程工厂批量创建虚拟线程
ThreadFactory factory = Thread.ofVirtual().factory();
Runnable task = () -> System.out.println("任务执行:" + Thread.currentThread());
factory.newThread(task).start();
}
}
🔹 2. 结构化并发(Structured Concurrency)
📌 简介
传统并发代码往往难以管理任务生命周期、错误处理和资源回收。
结构化并发是一种将多个子任务纳入统一作用域中进行调度和控制的新模型,更易于调试和维护。
✅ 场景
多个异步任务需并发执行并统一等待结果
某个任务失败后需快速取消其余任务
✅ 示例代码
import java.util.concurrent.*;
import jdk.incubator.concurrent.StructuredTaskScope;
public class StructuredConcurrencyDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<String> userFuture = scope.fork(() -> findUser());
Future<Integer> orderFuture = scope.fork(() -> fetchOrder());
scope.join();
scope.throwIfFailed(); // 若有异常会抛出
String user = userFuture.resultNow();
int order = orderFuture.resultNow();
System.out.println("结果:" + user + ", " + order);
}
}
static String findUser() {
return "张三";
}
static int fetchOrder() {
return 12345;
}
}
🔹 3. 模式匹配增强(Pattern Matching)
📌 简介
Java 21 在 switch、instanceof、record 模式等方面全面增强了模式匹配能力,让代码逻辑更清晰、分支判断更优雅。
✅ 新能力包括:
switch 表达式支持类型模式与守卫条件(
case T t && 条件)支持 record 解构匹配(如
Point(int x, int y))
✅ 示例代码
public class PatternMatchingDemo {
public static void main(String[] args) {
Object obj = 123;
String result = switch (obj) {
case String s -> "字符串:" + s;
case Integer i && i > 100 -> "大整数:" + i;
case null -> "是 null";
default -> "未知类型";
};
System.out.println(result);
}
}
🔹 4. 字符串模板(String Templates)
📌 简介
JDK 21 引入了全新的字符串插值机制 String Templates(预览特性),比传统字符串拼接更安全、更可扩展,能有效避免注入攻击。
✅ 特性亮点
支持嵌入表达式(如
${变量})语法简洁,支持自定义格式器(如 HTML、JSON)
编译时安全验证,防止 SQL/HTML 注入
✅ 示例代码(需开启预览特性)
// 需使用 --enable-preview 编译运行
import static java.util.FormatProcessor.FMT;
public class StringTemplateDemo {
public static void main(String[] args) {
String name = "小明";
int age = 20;
String result = FMT."姓名: \{name}, 年龄: \{age}";
System.out.println(result); // 输出:姓名: 小明, 年龄: 20
}
}
⚠️ 目前为 预览特性,需通过 --enable-preview 启用。
🔹 5. Sequenced Collections(有序集合接口)
📌 简介
新引入的 SequencedCollection、SequencedSet 和 SequencedMap 接口,统一了集合的顺序访问能力。
✅ 特性
提供
getFirst()、getLast()、reversed()等方法支持正序/反序遍历
✅ 示例代码
import java.util.*;
public class SequencedCollectionDemo {
public static void main(String[] args) {
SequencedSet<String> set = new LinkedHashSet<>();
set.add("A");
set.add("B");
set.add("C");
System.out.println("第一个元素: " + set.getFirst());
System.out.println("最后一个元素: " + set.getLast());
System.out.println("反转后: " + set.reversed());
}
}
🔹 6. Scoped Values(作用域值)
📌 简介
ScopedValue 是 ThreadLocal 的替代方案,用于在多线程执行期间传递不可变上下文变量。
✅ 优点
不会导致内存泄漏
可控作用域(自动清除)
与虚拟线程完美兼容
✅ 示例代码
import jdk.internal.vm.annotation.Contained;
public class ScopedValueDemo {
static final ScopedValue<String> userId = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.runWhere(userId, "abc123", () -> {
System.out.println("当前用户 ID: " + userId.get());
});
System.out.println("作用域外访问: " + ScopedValue.isBound(userId)); // false
}
}
🔹 7. 异步堆栈跟踪(Async Stack Trace)
📌 简介
JDK 21 在虚拟线程中默认启用了异步堆栈跟踪,能更清晰地展示异步调用链。
该特性为 JVM 层优化,无需用户显式编码。
🔹 8. Record 模式匹配(Record Patterns)
📌 简介
Record 模式匹配允许在 instanceof 检查或 switch 表达式中直接解构 record 对象字段,减少样板代码。
✅ 示例代码
传统写法
Object obj = new Point(3, 4);
if (obj instanceof Point) {
Point p = (Point) obj;
int x = p.x();
int y = p.y();
System.out.println("点坐标: " + x + ", " + y);
}
使用 Record 模式匹配
Object obj = new Point(3, 4);
if (obj instanceof Point(int x, int y)) {
System.out.println("点坐标: " + x + ", " + y);
}
结合 switch 使用
record Point(int x, int y) {}
record Circle(Point center, int radius) {}
public class RecordPatternDemo {
public static void main(String[] args) {
Object shape = new Circle(new Point(1, 2), 10);
String result = switch (shape) {
case Point(int x, int y) -> "这是一个点: (" + x + ", " + y + ")";
case Circle(Point(int x, int y), int r) -> "圆心: (" + x + ", " + y + "), 半径: " + r;
default -> "未知图形";
};
System.out.println(result);
}
}
✅ 特性优点
✅ 小结
升级 JDK 21,让你的 Java 编程更现代、更简洁。