2人参与 • 2026-08-15 • Windows
jdk 26 于 2026 年 3 月发布,是 jdk 25(lts)之后的第一个非 lts 版本。
本版本共有 10 个 jep,其中 5 个正式特性、4 个预览特性、1 个孵化特性。
jdk 26 在并发、网络、性能和安全方面均有重要改进。
jep 517 — http/3 client(http/3 客户端)。jdk 26 为 java.net.http.httpclient 添加了 http/3 协议支持,基于 quic 传输协议。
改进:
import java.net.http.*;
import java.net.uri;
import java.time.duration;
// ============ 1. 基本 http/3 请求 ============
// 创建支持 http/3 的客户端
httpclient client = httpclient.newbuilder()
.version(httpclient.version.http_3) // 优先使用 http/3
.connecttimeout(duration.ofseconds(10))
.build();
// 发送 get 请求
httprequest request = httprequest.newbuilder()
.uri(uri.create("https://api.example.com/data"))
.get()
.build();
httpresponse<string> response = client.send(request,
httpresponse.bodyhandlers.ofstring());
system.out.println("status: " + response.statuscode());
system.out.println("version: " + response.version()); // http_3
system.out.println("body: " + response.body());
// ============ 2. 异步 http/3 请求 ============
httpclient asyncclient = httpclient.newbuilder()
.version(httpclient.version.http_3)
.build();
asyncclient.sendasync(request, httpresponse.bodyhandlers.ofstring())
.thenapply(httpresponse::body)
.thenaccept(body -> system.out.println("async response: " + body))
.join();
// ============ 3. 协议版本回退 ============
// 设置 http/3 优先,服务器不支持时自动回退
httpclient fallbackclient = httpclient.newbuilder()
.version(httpclient.version.http_3) // 优先 http/3
// 如果服务器不支持 http/3,自动回退到 http/2 或 http/1.1
.build();
httpresponse<string> resp = fallbackclient.send(request,
httpresponse.bodyhandlers.ofstring());
// 检查实际使用的协议版本
system.out.println("actual version: " + resp.version());
// 可能输出: http_3, http_2, 或 http_1_1
// ============ 4. post 请求 ============
string jsonbody = """
{"name": "alice", "age": 30}
""";
httprequest postrequest = httprequest.newbuilder()
.uri(uri.create("https://api.example.com/users"))
.header("content-type", "application/json")
.post(httprequest.bodypublishers.ofstring(jsonbody))
.build();
httpresponse<string> postresp = client.send(postrequest,
httpresponse.bodyhandlers.ofstring());
system.out.println("created: " + postresp.statuscode()); // 201
// ============ 5. 并发请求(http/3 多路复用优势)============
// http/3 的多路复用无队头阻塞,并发性能更优
list<uri> uris = list.of(
uri.create("https://api.example.com/users/1"),
uri.create("https://api.example.com/users/2"),
uri.create("https://api.example.com/users/3"),
uri.create("https://api.example.com/users/4"),
uri.create("https://api.example.com/users/5")
);
// 所有请求在单个 quic 连接上多路复用
list<completablefuture<httpresponse<string>>> futures = uris.stream()
.map(uri -> httprequest.newbuilder(uri).get().build())
.map(req -> asyncclient.sendasync(req, httpresponse.bodyhandlers.ofstring()))
.tolist();
// 等待所有响应
list<string> bodies = futures.stream()
.map(completablefuture::join)
.map(httpresponse::body)
.tolist();
// ============ 6. 流式响应(大文件下载)============
httprequest downloadreq = httprequest.newbuilder()
.uri(uri.create("https://cdn.example.com/large-file.zip"))
.get()
.build();
httpresponse<inputstream> streamresp = client.send(downloadreq,
httpresponse.bodyhandlers.ofinputstream());
try (inputstream is = streamresp.body();
outputstream os = files.newoutputstream(path.of("download.zip"))) {
is.transferto(os);
}
// ============ 7. 配置超时和重试 ============
httpclient robustclient = httpclient.newbuilder()
.version(httpclient.version.http_3)
.connecttimeout(duration.ofseconds(5))
.followredirects(httpclient.redirect.normal)
.build();
httprequest timedreq = httprequest.newbuilder()
.uri(uri.create("https://api.example.com/slow"))
.timeout(duration.ofseconds(30)) // 请求级超时
.get()
.build();
// ============ 8. http/3 vs http/2 对比 ============
// | 特性 | http/2 | http/3 |
// |------|--------|--------|
// | 传输层 | tcp | quic (udp) |
// | 队头阻塞 | 有(tcp 层)| 无 |
// | 连接建立 | 1-2 rtt | 0-1 rtt |
// | 连接迁移 | 不支持 | 支持 |
// | 加密 | 可选 tls | 强制 tls 1.3 |
// | 多路复用 | 有(受 tcp 限制)| 有(无限制)|
// ============ 9. 与虚拟线程配合 ============
// http/3 + 虚拟线程 = 超高并发网络客户端
try (var executor = executors.newvirtualthreadpertaskexecutor()) {
list<future<string>> results = new arraylist<>();
for (int i = 0; i < 10_000; i++) {
final int id = i;
results.add(executor.submit(() -> {
httprequest req = httprequest.newbuilder()
.uri(uri.create("https://api.example.com/items/" + id))
.get()
.build();
return client.send(req, httpresponse.bodyhandlers.ofstring()).body();
}));
}
// 处理结果...
}
jep 516 — aot object caching(aot 对象缓存)。jdk 26 扩展了 jdk 24 引入的 aot 机制,支持缓存对象(不仅是类),并兼容所有 gc。
改进:
# ============ 1. 创建 aot 缓存(训练运行)============ # 第一次运行:记录类加载和对象创建信息 java -xx:aotmode=record -xx:aotcache=app.aot -jar app.jar # 应用正常运行,同时生成缓存文件 # ============ 2. 使用 aot 缓存启动 ============ # 后续运行:从缓存恢复,跳过大量初始化 java -xx:aotcache=app.aot -jar app.jar # ============ 3. 与不同 gc 配合使用 ============ # g1 gc(默认) java -xx:aotcache=app.aot -jar app.jar # zgc java -xx:+usezgc -xx:aotcache=app.aot -jar app.jar # shenandoah java -xx:+useshenandoahgc -xx:aotcache=app.aot -jar app.jar # parallel gc java -xx:+useparallelgc -xx:aotcache=app.aot -jar app.jar # ============ 4. jdk 24 vs jdk 26 aot 对比 ============ # jdk 24(jep 483): # - 只缓存类加载和链接信息 # - 只支持默认 gc 配置 # jdk 26(jep 516): # - 缓存类加载 + 对象实例 # - 支持所有 gc # - 启动加速效果更显著 # ============ 5. 启动时间对比(典型 spring boot 应用)============ # 无优化:~3.5 秒 # cds(jdk 13+):~2.8 秒 # aot 类加载(jdk 24):~1.5 秒 # aot 对象缓存(jdk 26):~0.8 秒 # ============ 6. 容器化部署 ============ # dockerfile from eclipse-temurin:26-jdk as builder copy app.jar /app/app.jar # 训练运行生成缓存 run java -xx:aotmode=record -xx:aotcache=/app/app.aot -jar /app/app.jar --init-only from eclipse-temurin:26-jre copy --from=builder /app/app.jar /app/app.jar copy --from=builder /app/app.aot /app/app.aot entrypoint ["java", "-xx:aotcache=/app/app.aot", "-jar", "/app/app.jar"] # ============ 7. 注意事项 ============ # - aot 缓存与 jdk 版本绑定 # - 缓存文件包含应用状态信息(注意安全) # - 动态生成的类/对象可能无法缓存 # - 缓存文件大小取决于应用复杂度 # - 建议在 ci/cd 中生成缓存
jep 522 — g1 gc throughput improvement(g1 gc 吞吐量提升)。jdk 26 通过减少同步开销(双卡表机制)显著提升了 g1 gc 的吞吐量。
改进:
# ============ 1. 默认启用(无需配置)============ # jdk 26 中 g1 gc 自动使用优化后的实现 java -jar app.jar # 显式指定 g1(默认就是 g1) java -xx:+useg1gc -jar app.jar # ============ 2. 监控 g1 性能 ============ # gc 日志 java -xx:+useg1gc -xlog:gc*:file=gc.log:time,level,tags -jar app.jar # 查看 gc 统计 java -xx:+useg1gc -xlog:gc+stats=info -jar app.jar # ============ 3. 性能对比 ============ # jdk 25 g1 vs jdk 26 g1(高并发场景): # - 吞吐量提升:5%-15% # - gc 暂停时间:基本不变 # - 内存占用:基本不变 # - cpu 利用率:更高效 # ============ 4. 适用场景 ============ # 受益最大的场景: # - 高并发 web 服务(大量虚拟线程/平台线程) # - 写密集型应用(频繁对象创建) # - 大堆应用(> 8gb) # - 多线程数据处理管道 # ============ 5. g1 常用调优参数(jdk 26)============ # 目标暂停时间 java -xx:+useg1gc -xx:maxgcpausemillis=200 -jar app.jar # 堆大小 java -xx:+useg1gc -xms4g -xmx4g -jar app.jar # 区域大小 java -xx:+useg1gc -xx:g1heapregionsize=16m -jar app.jar # 混合 gc 触发阈值 java -xx:+useg1gc -xx:initiatingheapoccupancypercent=45 -jar app.jar
jep 500 — final field integrity(终态字段完整性)。jdk 26 加强了 final 字段的不可变性保证,通过反射修改 final 字段时会产生警告。
改进:
import java.lang.reflect.field;
// ============ 1. 问题背景 ============
class config {
final string env = "production";
final int maxretries = 3;
}
// jdk 25 及之前:可以通过反射修改 final 字段(危险!)
config cfg = new config();
field f = config.class.getdeclaredfield("env");
f.setaccessible(true);
f.set(cfg, "development"); // jdk 25: 静默成功
system.out.println(cfg.env); // "development" — 破坏了不可变性!
// ============ 2. jdk 26 行为变化 ============
// jdk 26:反射修改 final 字段会产生警告
config cfg2 = new config();
field f2 = config.class.getdeclaredfield("env");
f2.setaccessible(true);
f2.set(cfg2, "staging");
// 控制台输出警告:
// warning: illegal reflective access to final field 'env' in class config
// warning: this operation will be disallowed in a future release
system.out.println(cfg2.env); // 行为可能不确定
// ============ 3. 正确的替代方案 ============
// 方案一:使用不可变设计(推荐)
record appconfig(string env, int maxretries) {}
appconfig config = new appconfig("production", 3);
// config.env() 永远不可变
// 方案二:使用 setter(如果确实需要可变)
class mutableconfig {
private string env = "production";
public string getenv() { return env; }
public void setenv(string env) { this.env = env; }
}
// 方案三:使用 atomicreference(并发安全的可变)
class concurrentconfig {
private final atomicreference<string> env =
new atomicreference<>("production");
public string getenv() { return env.get(); }
public void setenv(string newenv) { env.set(newenv); }
}
// ============ 4. 框架迁移指南 ============
// 许多序列化/反序列化框架依赖反射修改 final 字段
// jdk 26 中这些框架需要更新:
// 旧方式(框架内部):
// field field = obj.getclass().getdeclaredfield("id");
// field.setaccessible(true);
// field.set(obj, deserializedvalue); // jdk 26 产生警告
// 新方式(框架应使用):
// 1. 使用构造器注入(推荐)
// 2. 使用 varhandle
// 3. 使用 methodhandle
// 4. 使用 unsafe(临时方案,最终也会被限制)
// ============ 5. 检测项目中的问题代码 ============
// 运行时添加参数检测所有反射修改 final 字段的位置:
// java -djava.lang.reflect.finalfield.warning=verbose -jar app.jar
// 编译时检查:
// javac -xlint:all myclass.java
// ============ 6. 时间线 ============
// jdk 26:反射修改 final 字段 → 产生警告
// 未来版本:反射修改 final 字段 → 抛出异常
// 建议:尽早迁移,不要依赖反射修改 final 字段
jep 504 — remove the applet api(移除 applet api)。jdk 26 彻底移除了 java.applet 包中的所有类。
改进:
java.applet.applet 类java.applet.appletcontext 等接口// ============ 1. 已移除的类 ============ // 以下类在 jdk 26 中不再存在: // - java.applet.applet // - java.applet.appletcontext // - java.applet.appletstub // - java.applet.audioclip // 编译使用这些类的代码会报错: // error: package java.applet does not exist // ============ 2. 迁移方案 ============ // 如果有遗留 applet 代码,迁移选择: // 方案一:迁移到 java web start(也已弃用)→ 桌面应用 // 方案二:迁移到 javafx 富客户端 // 方案三:迁移到 web 技术(html5 + javascript) // 方案四:迁移到服务端渲染 + rest api // ============ 3. 检查依赖 ============ // 检查项目是否依赖 applet api: // grep -r "java.applet" src/ // grep -r "extends applet" src/ // grep -r "import java.applet" src/ // 大多数现代项目不会受影响 // applet 技术已被淘汰超过 10 年
jep 525 — structured concurrency(结构化并发,第六次预览)。jdk 26 为结构化并发添加了超时支持(joiner 超时),进一步简化并发编程。
改进:
joiner.ontimeout() — 超时后返回默认值joiner.anysuccessfulorthrow() 超时变体import java.util.concurrent.structuredtaskscope;
import java.util.concurrent.structuredtaskscope.joiner;
import java.util.concurrent.structuredtaskscope.subtask;
// ============ 1. 基本并行聚合(与之前版本相同)============
record userprofile(user user, list<order> orders) {}
userprofile fetchprofile(string userid) throws exception {
try (var scope = structuredtaskscope.open(
joiner.<object>allsuccessfulorthrow())) {
subtask<user> user = scope.fork(() -> getuser(userid));
subtask<list<order>> orders = scope.fork(() -> getorders(userid));
scope.join();
return new userprofile(user.get(), orders.get());
}
}
// ============ 2. 新增:超时 joiner ============
// 超时后返回默认值,而非抛异常
response handlewithtimeout(string requestid) throws exception {
try (var scope = structuredtaskscope.open(
joiner.anysuccessfulorthrow(),
builder -> builder.withtimeout(duration.ofmillis(300)))) {
scope.fork(() -> callprimaryservice(requestid));
scope.fork(() -> callsecondaryservice(requestid));
scope.join();
return scope.result();
} catch (timeoutexception e) {
return response.fallback(); // 超时返回默认响应
}
}
// ============ 3. 超时 + 默认值 joiner ============
string fetchwithfallback(string url) throws exception {
try (var scope = structuredtaskscope.open(
joiner.ontimeout(duration.ofseconds(2), () -> "cached-default"))) {
scope.fork(() -> httpget(url));
scope.fork(() -> httpgetmirror(url));
scope.join();
return scope.result(); // 超时则返回 "cached-default"
}
}
// ============ 4. 竞速模式(取最快结果)============
<t> t race(list<callable<t>> tasks) throws exception {
try (var scope = structuredtaskscope.open(
joiner.<t>anysuccessfulorthrow())) {
tasks.foreach(scope::fork);
scope.join();
return scope.result();
}
}
// 使用:从多个 cdn 取最快的
string content = race(list.of(
() -> fetchfromcdn1(path),
() -> fetchfromcdn2(path),
() -> fetchfromcdn3(path)
));
// ============ 5. 批量处理 + 超时 ============
list<result> processbatch(list<task> tasks) throws exception {
try (var scope = structuredtaskscope.open(
joiner.allsuccessfulorthrow(),
builder -> builder.withtimeout(duration.ofseconds(30)))) {
list<subtask<result>> subtasks = tasks.stream()
.map(t -> scope.fork(() -> execute(t)))
.tolist();
scope.join();
return subtasks.stream()
.map(subtask::get)
.tolist();
}
}
// ============ 6. 与虚拟线程配合 ============
// structuredtaskscope 内部自动使用虚拟线程
// 可以轻松 fork 大量子任务
try (var scope = structuredtaskscope.open(
joiner.allsuccessfulorthrow())) {
for (int i = 0; i < 10_000; i++) {
final int id = i;
scope.fork(() -> processitem(id));
}
scope.join();
}
// ============ 7. 错误处理策略 ============
// 策略一:全部成功或抛异常
joiner.allsuccessfulorthrow()
// 策略二:任一成功即返回
joiner.anysuccessfulorthrow()
// 策略三:超时返回默认值
joiner.ontimeout(duration.ofseconds(5), () -> defaultvalue)
// 策略四:自定义 joiner
joiner<object> custom = joiner.of(completedsubtasks -> {
// 自定义完成逻辑
return completedsubtasks.stream()
.filter(s -> s.state() == subtask.state.success)
.map(subtask::get)
.tolist();
});
jep 530 — primitive types in patterns(原始类型模式,第四次预览)。jdk 26 继续改进原始类型在模式匹配中的支持,接近最终定稿。
改进:
instanceof 和 switch 全面支持所有原始类型// ============ 1. switch 匹配所有原始类型 ============
string format(object value) {
return switch (value) {
case byte b -> "0x" + integer.tohexstring(b & 0xff);
case short s -> "short:" + s;
case int i -> "int:" + i;
case long l -> "long:" + l;
case float f -> string.format("%.2f", f);
case double d -> string.format("%.4f", d);
case char c -> "'" + c + "'";
case boolean b -> b ? "yes" : "no";
case string s -> "\"" + s + "\"";
default -> "unknown";
};
}
// ============ 2. 带守卫的模式 ============
string classifyprice(object price) {
return switch (price) {
case int p when p < 100 -> "budget";
case int p when p < 500 -> "mid-range";
case int p -> "premium";
case double d when d < 100.0 -> "budget";
case double d -> "premium";
default -> "unknown";
};
}
// ============ 3. 与 record patterns 配合 ============
record sensorreading(string sensor, object value, long timestamp) {}
void processreading(sensorreading reading) {
switch (reading) {
case sensorreading("temperature", double d, _) ->
system.out.printf("temp: %.1f°c%n", d);
case sensorreading("pressure", int p, _) ->
system.out.printf("pressure: %d hpa%n", p);
case sensorreading("active", boolean b, _) ->
system.out.println("active: " + b);
default ->
system.out.println("unknown reading: " + reading.sensor());
}
}
// ============ 4. 数值解析与分发 ============
void handleinput(object input) {
switch (input) {
case int i -> handleinteger(i);
case long l -> handlelong(l);
case double d -> handledouble(d);
case boolean b -> handleboolean(b);
case char c -> handlechar(c);
case string s -> handlestring(s);
case null -> handlenull();
default -> handleunknown(input);
}
}
// ============ 5. 安全窄化 ============
void narrowdemo(object obj) {
switch (obj) {
// long 值如果在 int 范围内,可以匹配 int 模式
case int i -> system.out.println("int: " + i);
case long l -> system.out.println("long only: " + l);
default -> system.out.println("not a number");
}
}
narrowdemo(42); // int: 42
narrowdemo(42l); // int: 42(在 int 范围内)
narrowdemo(5_000_000_000l); // long only: 5000000000
jep 524 — pem encoding of cryptographic objects(pem 编码 api,第二次预览)。jdk 26 继续改进 pem 编码/解码 api,支持将密码学对象与 pem 格式互相转换。
改进:
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
// ============ 1. 公钥编码为 pem ============
// 生成 rsa 密钥对
keypairgenerator kpg = keypairgenerator.getinstance("rsa");
kpg.initialize(2048);
keypair keypair = kpg.generatekeypair();
// 编码公钥为 pem 字符串
pemencoder encoder = pemencoder.of();
string publickeypem = encoder.encodetostring(keypair.getpublic());
system.out.println(publickeypem);
// -----begin public key-----
// miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqea...
// -----end public key-----
// ============ 2. 私钥编码为 pem ============
string privatekeypem = encoder.encodetostring(keypair.getprivate());
system.out.println(privatekeypem);
// -----begin private key-----
// miievgibadanbgkqhkig9w0baqefaascbkgwggskageaao...
// -----end private key-----
// ============ 3. 从 pem 解码为密钥对象 ============
pemdecoder decoder = pemdecoder.of();
// 解码公钥
publickey restoredpublic = decoder.decode(publickeypem);
system.out.println("algorithm: " + restoredpublic.getalgorithm()); // rsa
// 解码私钥
privatekey restoredprivate = decoder.decode(privatekeypem);
// ============ 4. 从文件读取 pem ============
// 读取 pem 文件
string pemcontent = files.readstring(path.of("server.crt"));
publickey certkey = decoder.decode(pemcontent);
// 读取私钥文件
string keycontent = files.readstring(path.of("server.key"));
privatekey serverkey = decoder.decode(keycontent);
// ============ 5. 写入 pem 文件 ============
// 保存公钥
files.writestring(path.of("public.pem"),
encoder.encodetostring(keypair.getpublic()));
// 保存私钥
files.writestring(path.of("private.pem"),
encoder.encodetostring(keypair.getprivate()));
// ============ 6. ec 密钥的 pem 编码 ============
keypairgenerator eckpg = keypairgenerator.getinstance("ec");
eckpg.initialize(new ecgenparameterspec("secp256r1"));
keypair eckeypair = eckpg.generatekeypair();
string ecpublicpem = encoder.encodetostring(eckeypair.getpublic());
string ecprivatepem = encoder.encodetostring(eckeypair.getprivate());
// ============ 7. ml-kem / ml-dsa 密钥的 pem 编码 ============
// 抗量子密钥也可以编码为 pem
keypairgenerator mlkpg = keypairgenerator.getinstance("ml-kem");
mlkpg.initialize(new namedparameterspec("ml-kem-768"));
keypair mlkeypair = mlkpg.generatekeypair();
string mlpublicpem = encoder.encodetostring(mlkeypair.getpublic());
string mlprivatepem = encoder.encodetostring(mlkeypair.getprivate());
// ============ 8. 证书 pem 编码 ============
// x.509 证书编码
certificatefactory cf = certificatefactory.getinstance("x.509");
x509certificate cert = (x509certificate) cf.generatecertificate(
files.newinputstream(path.of("ca.crt")));
string certpem = encoder.encodetostring(cert);
// -----begin certificate-----
// miic...
// -----end certificate-----
// ============ 9. 实际应用场景 — tls 证书配置 ============
// 从 pem 文件加载 tls 证书和私钥
string certpem = files.readstring(path.of("tls/server.crt"));
string keypem = files.readstring(path.of("tls/server.key"));
publickey tlspublic = decoder.decode(certpem);
privatekey tlsprivate = decoder.decode(keypem);
// 用于配置 sslcontext
keystore ks = keystore.getinstance("pkcs12");
ks.load(null, null);
ks.setkeyentry("server", tlsprivate, "changeit".tochararray(),
new java.security.cert.certificate[]{(java.security.cert.certificate) decoder.decode(certpem)});
// ============ 10. 与手动 base64 方式对比 ============
// 传统手动方式(繁琐且易错):
string manualpem = "-----begin public key-----\n" +
base64.getmimeencoder(64, "\n".getbytes())
.encodetostring(keypair.getpublic().getencoded()) +
"\n-----end public key-----\n";
// jdk 26 pem api(简洁安全):
string apipem = pemencoder.of().encodetostring(keypair.getpublic());
jep 526 — lazy constants(延迟常量,第二次预览)。jdk 26 引入 lazyconstant api,提供线程安全的延迟初始化机制,替代 static final 急切初始化和双重检查锁定模式。
改进:
static final 急切初始化(加速启动)import java.lang.lazyconstant;
// ============ 1. 基本用法 ============
// 延迟初始化一个昂贵的对象
private final lazyconstant<databaseconnection> dbconnection =
lazyconstant.of(() -> databaseconnection.create("jdbc:mysql://localhost/app"));
// 第一次访问时初始化
void query() {
databaseconnection conn = dbconnection.get(); // 首次调用触发初始化
conn.execute("select ...");
}
// 后续访问直接返回缓存值(零开销)
void anotherquery() {
databaseconnection conn = dbconnection.get(); // 直接返回,无同步开销
conn.execute("select ...");
}
// ============ 2. 替代 static final 急切初始化 ============
// 传统方式:类加载时就初始化(拖慢启动)
class appcontext {
// 即使不使用也会初始化
private static final logger logger = logger.create(appcontext.class);
private static final config config = config.load();
private static final metricsregistry metrics = new metricsregistry();
}
// jdk 26 方式:按需初始化(加速启动)
class appcontext {
private static final lazyconstant<logger> logger =
lazyconstant.of(() -> logger.create(appcontext.class));
private static final lazyconstant<config> config =
lazyconstant.of(() -> config.load());
private static final lazyconstant<metricsregistry> metrics =
lazyconstant.of(() -> new metricsregistry());
void handlerequest() {
// 只有实际使用时才初始化
logger.get().info("processing request");
config cfg = config.get();
}
}
// ============ 3. 替代双重检查锁定(dcl)============
// 传统 dcl 模式(复杂且易错)
class singleton {
private static volatile singleton instance;
public static singleton getinstance() {
if (instance == null) {
synchronized (singleton.class) {
if (instance == null) {
instance = new singleton();
}
}
}
return instance;
}
}
// jdk 26 lazyconstant(简洁安全)
class singleton {
private static final lazyconstant<singleton> instance =
lazyconstant.of(singleton::new);
public static singleton getinstance() {
return instance.get();
}
}
// ============ 4. 替代 holder 模式 ============
// 传统 holder 模式
class expensiveservice {
private static class holder {
static final expensiveservice instance = new expensiveservice();
}
public static expensiveservice getinstance() {
return holder.instance;
}
}
// jdk 26 lazyconstant
class expensiveservice {
private static final lazyconstant<expensiveservice> instance =
lazyconstant.of(expensiveservice::new);
public static expensiveservice getinstance() {
return instance.get();
}
}
// ============ 5. 实例级延迟初始化 ============
class ordercontroller {
// 每个实例独立延迟初始化
private final lazyconstant<logger> logger =
lazyconstant.of(() -> logger.create(ordercontroller.class));
private final lazyconstant<ordervalidator> validator =
lazyconstant.of(() -> new ordervalidator(loadrules()));
void handleorder(order order) {
logger.get().debug("processing order: " + order.id());
validator.get().validate(order);
}
}
// ============ 6. 条件性初始化 ============
class featureflags {
private final lazyconstant<map<string, boolean>> flags =
lazyconstant.of(() -> {
// 只在第一次访问时从远程加载
return remoteconfigservice.fetchflags();
});
boolean isenabled(string feature) {
return flags.get().getordefault(feature, false);
}
}
// ============ 7. 与虚拟线程配合 ============
// lazyconstant 在虚拟线程环境中同样安全高效
class requesthandler {
private final lazyconstant<heavyresource> resource =
lazyconstant.of(() -> heavyresource.initialize());
void handle() {
// 多个虚拟线程并发调用 get()
// 只有一个线程执行初始化,其他等待
heavyresource r = resource.get();
r.process();
}
}
// ============ 8. 性能特点 ============
// | 方式 | 线程安全 | 初始化后开销 | 代码复杂度 |
// |------|----------|-------------|-----------|
// | static final | 是 | 零 | 低 |
// | synchronized | 是 | 每次加锁 | 中 |
// | dcl | 是 | volatile 读 | 高 |
// | holder | 是 | 零 | 中 |
// | lazyconstant | 是 | 零(jvm 内联)| 低 |
// lazyconstant 的优势:
// - 延迟初始化(不拖慢启动)
// - 初始化后零开销(jvm 可内联)
// - 代码简洁(一行声明)
// - 线程安全(无需手动同步)
// ============ 9. 注意事项 ============
// - lazyconstant 是不可变的(一旦设置不能更改)
// - 初始化函数不应有副作用(或确保幂等)
// - 如果初始化抛异常,后续 get() 会重新尝试
// - 不适合需要重新初始化的场景(用 atomicreference)
// - 编译运行需要启用预览:
// javac --enable-preview --source 26 app.java
// java --enable-preview app
jep 529 — vector api(向量 api,第十一次孵化)。jdk 26 继续孵化向量 api,等待 project valhalla 值类型支持后正式标准化。
import jdk.incubator.vector.*;
static final vectorspecies<float> species = floatvector.species_256;
// 向量加法
void add(float[] a, float[] b, float[] c) {
int i = 0;
for (; i < species.loopbound(a.length); i += species.length()) {
floatvector va = floatvector.fromarray(species, a, i);
floatvector vb = floatvector.fromarray(species, b, i);
va.add(vb).intoarray(c, i);
}
for (; i < a.length; i++) c[i] = a[i] + b[i];
}
// 点积
float dot(float[] a, float[] b) {
floatvector sum = floatvector.zero(species);
int i = 0;
for (; i < species.loopbound(a.length); i += species.length()) {
sum = floatvector.fromarray(species, a, i)
.fma(floatvector.fromarray(species, b, i), sum);
}
float r = sum.reducelanes(vectoroperators.add);
for (; i < a.length; i++) r += a[i] * b[i];
return r;
}
// 编译: javac --add-modules jdk.incubator.vector vecdemo.java
// 运行: java --add-modules jdk.incubator.vector vecdemo
| 序号 | 特性 | jep | 类型 | 状态 | 重要性 |
|---|---|---|---|---|---|
| 1 | http/3 client | jep 517 | 网络 | 正式 | ★★★★★ |
| 2 | aot object caching | jep 516 | 性能 | 正式 | ★★★★★ |
| 3 | g1 gc throughput improvement | jep 522 | gc | 正式 | ★★★★☆ |
| 4 | final field integrity | jep 500 | 安全 | 正式 | ★★★★☆ |
| 5 | remove applet api | jep 504 | 清理 | 正式 | ★★☆☆☆ |
| 6 | structured concurrency(超时 joiner) | jep 525 | 并发 | 第六次预览 | ★★★★★ |
| 7 | primitive types in patterns | jep 530 | 语言 | 第四次预览 | ★★★★★ |
| 8 | pem encoding api | jep 524 | 安全 | 第二次预览 | ★★★★☆ |
| 9 | lazy constants | jep 526 | api | 第二次预览 | ★★★★★ |
| 10 | vector api | jep 529 | api | 第十一次孵化 | ★★★☆☆ |
| 特性 | jdk 23 | jdk 24 | jdk 25 | jdk 26 |
|---|---|---|---|---|
| structured concurrency | 第三次预览 | 第四次预览 | 第五次预览 | 第六次预览 |
| primitive types in patterns | 预览 | 第二次预览 | 第三次预览 | 第四次预览 |
| pem encoding api | — | — | 预览 | 第二次预览 |
| lazy constants (stable values) | — | — | 预览 | 第二次预览 |
| vector api | 第八次孵化 | 第九次孵化 | 第十次孵化 | 第十一次孵化 |
| stream gatherers | 第二次预览 | 正式 | — | — |
| class-file api | 第二次预览 | 正式 | — | — |
| scoped values | 第三次预览 | 第四次预览 | 正式 | — |
| module import declarations | 预览 | 第二次预览 | 正式 | — |
| simple source files | 第三次预览 | 第四次预览 | 正式 | — |
| flexible constructor bodies | 第二次预览 | 第三次预览 | 正式 | — |
| kdf api | — | 预览 | 正式 | — |
| 项目 | 说明 |
|---|---|
| 发布日期 | 2026年3月 |
| 版本类型 | 非 lts(短期支持) |
| 前一个版本 | jdk 25(lts,2025年9月) |
| 下一个版本 | jdk 27(2026年9月) |
| 下一个 lts | jdk 29(预计 2027年9月) |
| 主要意义 | 后 lts 创新版本,引入 http/3 和延迟常量等重要特性 |
jdk 26 的关键贡献:
总结:jdk 26 是 jdk 25 lts 之后的第一个创新版本,在多个方向带来重要突破。http/3 客户端 让 java 原生支持基于 quic 的现代网络协议;aot 对象缓存 将启动加速从类加载扩展到对象级别;lazy constants 提供了优雅的延迟初始化方案,替代了复杂的 dcl 和 holder 模式;g1 gc 吞吐量提升 让默认 gc 在高并发场景下表现更好;final 字段完整性 加强了 java 的不可变性保证。结构化并发和原始类型模式等预览特性继续演进,为后续版本定稿做准备
到此这篇关于jdk26新特性超详细讲解的文章就介绍到这了,更多相关jdk26新特性内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论