#JDK 17 新特性
/****************
文本块
*****************/
python/scala中早就支持,不稀奇
String json = “”"
{
“name”: “Java”,
“version”: 17
}
“”";
/****************
var
*****************/
var 并非动态类型,而是编译时根据初始化表达式推断变量类型,生成字节码时替换为具体类型
var strings = List.of(“a”,“b”,“b”);
for (var str : strings) { // 推断为 Integer
System.out.print(str + " "); // 10 20 30
}
/****************
Switch 语句 + -> 表达式
*****************/
挺好的,格式漂亮,带有返回值。干劲利落。
没有break穿透问题
带有yield
String result = switch (operation) {
case "A" -> {
System.out.println("Success");
yield "Success";
}
case "B" -> {
yield error ? "Error" : "Valid";
} // Java 17 支持直接返回表达式
default -> throw new IllegalArgumentException("Invalid operation");
};
/****************
String类的新方法
repeat:重复生成字符串
isBlank:不用在引入第三方库就可以实现字符串判空了
strip:去除字符串两边的空格,支持全角和半角,之前的trim只支持半角
lines:能根据一段字符串中的终止符提取出行为单位的流
indent:给字符串做缩进,接受一个int型的输入
transform:接受一个转换函数,实现字符串的转换
但是Hutool里面的功能不是更多么?
/****************
Pattern 类增强功能
****************/
替代传统 str.matches(regex),直接集成到 Stream API 中
可以不使用regular expression
复杂正则匹配效率提升 10%~30%,尤其对长文本和大规模数据。
相当于python 中的 rf""
匹配路径 “C:\Windows\System”:
- 手动转义: C:\\Windows\\System
- 使用 \Q…\E: \QC:\Windows\System\E
/****************
NullPointerException 信息增强
*****************/
//仅提示 NullPointerException,不明确具体原因
String s = null;
s.toLowerCase(); // 输出:java.lang.NullPointerException
String s = null;
s.toLowerCase(); // 输出:java.lang.NullPointerException: Cannot invoke “String.toLowerCase()” because “s” is null
/****************
obj instanceof String
*****************/
// JDK 8:需显式转换,可能引发 ClassCastException
if (obj instanceof String) {
String str = (String) obj; // 转换可能失败
System.out.println(str.toUpperCase());
}
// JDK 17:直接绑定变量,类型安全
if (obj instanceof String str) {
System.out.println(str.toUpperCase()); // 无需转换
}
/****************
集合类工厂方法
*****************/
只对返回值,或者Enum类有用。对于大型参数,一定是读取数据库或者缓存
原先需要通过Array转,现在可以直接用。 看源码没什么花头,就是Array加强制转换
List list = List.of(99,999,999,999);
List Arrays.asList(“a”, “b”, “c”) ->>> /*17 */ List.of(“a”, “b”, “c”)
Set new HashSet<>(Arrays.asList(“a”,“b”)) ->>> /*17 */ Set.of(“a”, “b”)
Map 手动 put 或依赖 Guava 等三方库 ->>> /*17 */ Map.of(“a”, 1, “b”, 2) 或 Map.ofEntries(…)
/****************
Records
*****************/
- 相当于scala中的case class, 但无法动态编译。也没达到python Django 中model 的高度,感觉有点鸡肋
- 可以用来结合JSON做序列化和反序列化。但没有fastjson + dataframe好用
- Spark RDD + dataframe 的做法非常好
- Reflection + Records 会比较好用
/****************
Sealed class
****************/
public sealed class Shape permits Circle, Rectangle
对业务开发没有感觉
在架构开发中有一定作用
类似于Abstract class,也类似于Generic泛型,但可对单个 class 进行点名限制
/****************
interface 中的私有静态方法
*****************/
对业务开发没有感觉
在架构开发中有一定作用, 增强安全性
/****************
内部静态类
****************/
//只能静态访问静态。但是静态类是线程安全的
//对返回值,Enum类封装比较有效。但因为增加代码复杂度,不符合clean code 规范
package org.example.newFeatures.StaticNestedClass;
public class StaticNestedClass {
private String name = “外部类实例字段”;
private static String STATIC_FIELD = “外部类静态字段”;
// 静态嵌套类(Static Nested Class)
public static class StaticNestedClass1 {
public void print() {
System.out.println(STATIC_FIELD); // ✅ 直接访问外部类静态成员
//System.out.println(name); // ❌ 编译错误:无法访问实例字段
}
}
// 内部类(Inner Class)
public class InnerClass {
public void print() {
System.out.println(name); // ✅ 访问外部类实例字段
System.out.println(STATIC_FIELD); // ✅ 访问外部类静态字段
}
}
public static void main(String[] args) {
StaticNestedClass.StaticNestedClass1 staticNestedClass1 = new StaticNestedClass.StaticNestedClass1();
staticNestedClass1.print();
StaticNestedClass staticNestedClass = new StaticNestedClass();
StaticNestedClass.InnerClass innerClass = staticNestedClass.new InnerClass();
innerClass.print();
}
}
/****************
instance of 功能很棒
JDK17新特性6 - 模式匹配,避免了强制转换
*****************/
if (obj instanceof String s) {
System.out.println(s.toUpperCase()); // 直接使用变量 s
}
/****************
Transform 流式处理
****************/
//stream表达式太长,调试不方便。
//除非有特定性能要求,一般不使用
public void transformTest3_filter() {
List numbers = List.of(10, 3, 8, 15, 6, 1);
// 保留大于5的偶数 [8, 6]
List result = numbers.stream()
.filter(n -> n > 5 && n % 2 == 0)
.toList();
System.out.println(result);
}
/****************
List.of
****************/
List words = List.of(“Java”, “JDK17”, “Pattern”, “OpenJDK”);
//实际上是做了个封装,然后强制转换
//不可写,因为List.of产生的list是只读的。
static {
CDS.initializeFromArchive(ImmutableCollections.class);
if (archivedObjects == null) {
EMPTY = new Object();
EMPTY_LIST = new ListN<>(new Object[0], false);
EMPTY_LIST_NULLS = new ListN<>(new Object[0], true);
EMPTY_SET = new SetN<>();
EMPTY_MAP = new MapN<>();
archivedObjects =
new Object[] { EMPTY, EMPTY_LIST, EMPTY_LIST_NULLS, EMPTY_SET, EMPTY_MAP };
} else {
EMPTY = archivedObjects[0];
EMPTY_LIST = (ListN)archivedObjects[1];
EMPTY_LIST_NULLS = (ListN)archivedObjects[2];
EMPTY_SET = (SetN)archivedObjects[3];
EMPTY_MAP = (MapN)archivedObjects[4];
}
}
/****************
Stream API 增强
****************/
List list = Stream.of(1, 2, 3).filter(x -> x > 1).toList();
/****************
Http Request 异步处理
****************/
private CompletableFuture<HttpResponse>
sendAsync(HttpRequest userRequest,
BodyHandler responseHandler,
PushPromiseHandler pushPromiseHandler,
Executor exchangeExecutor)
/****************
web socket 比较
****************/
特性 JDK 8 JDK 17
I/O 模型 基于阻塞式 I/O(BIO) 异步 NIO(非阻塞),支持高并发
资源消耗 每个连接占用一个线程,并发能力受限 基于 Selector 多路复用,线程复用率高
HTTP/2 支持 无原生支持 原生支持 HTTP/2,提升传输效率
/****************
JDK 17中的Vector API用于做什么
****************/
金融建模(蒙特卡洛模拟优化), 但问题是Python中有其他的量化库。 挺有意思,但java写在底层有什么意义?
真正的模拟我会放在 spark 中做分布式计算
Incubator 功能,感觉挺鸡肋的
场景优势:
吞吐量:单次模拟处理 8 组数据,性能达 850 万次/秒(标量仅 120 万次/秒)
精度保障:内置 sqrt() 等数学函数支持向量化计算
FloatVector simulatePayoff(float strikePrice) {
FloatVector rand1 = generateRandomVector(SPECIES); // 生成随机数向量
FloatVector rand2 = generateRandomVector(SPECIES);
// 并行计算期权收益:sqrt(rand1*rand2) - strikePrice
FloatVector payoff = rand1.mul(rand2)
.sqrt()
.sub(strikePrice)
.max(0); // 收益最小为0
return payoff;
}
/****************
NEW IO
****************/
//Channel + Buffer + Select 是NIO的核心
//这类有2GB内存限制,用起来要小心
String content = Files.readString(path);
//异步读取设计不错
// 4. 发起异步读取操作(从文件位置0开始)
Future readResult = channel.read(buffer, 0);
// 5. 非阻塞等待(可在此处执行其他任务)
System.out.println(“主线程继续执行其他任务…”);
while (!readResult.isDone()) {
Thread.sleep(100); // 避免CPU空转3,5
System.out.print(“.”);
}
//java 源码刨析
/ public abstract class AsynchronousFileChannel
// – reading and writing –
// 利用了Future对象的异步返回
abstract Future implRead(ByteBuffer dst,
long position,
A attachment,
CompletionHandler<Integer,? super A> handler);
/****************
JDK 17中对于并发编程的改进有哪些
****************/
###StampedLock的改进,提高了并发编程的效率, 增强了线程池的安全控制
StampledLock的秘密在于,源码中定义了一系列的node, 然后通过acquire readNode, 找到这个node的状态,然后 break 无限循环 。。。。
喜欢这个大胆粗暴的想法
public class StampedLock implements java.io.Serializable {
private long acquireRead(boolean interruptible, boolean timed, long time) {
boolean interrupted = false;
ReaderNode node = null;
/*
* Loop:
* if empty, try to acquire
* if tail is Reader, try to cowait; restart if leader stale or cancels
* else try to create and enqueue node, and wait in 2nd loop below
*/
for (;;) {
ReaderNode leader; long nextState;
Node tailPred = null, t = tail;
if ((t == null || (tailPred = t.prev) == null) &&
(nextState = tryAcquireRead()) != 0L) // try now if empty
return nextState;
else if (t == null)
tryInitializeHead();
else if (tailPred == null || !(t instanceof ReaderNode)) {
if (node == null)
node = new ReaderNode();
if (tail == t) {
node.setPrevRelaxed(t);
if (casTail(t, node)) {
t.next = node;
break; // node is leader; wait in loop below
}
node.setPrevRelaxed(null);
}
###/线程安全终止
workerThread.interrupt(); // 安全终止
源码中就是那么简单和清爽
public void interrupt() {
if (this != Thread.currentThread()) {
checkAccess();
// thread may be blocked in an I/O operation
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupted = true;
interrupt0(); // inform VM of interrupt
b.interrupt(this);
return;
}
}
}
interrupted = true;
// inform VM of interrupt
interrupt0();
}
动态扩容(JDK 17 新增校验)
executor.setCorePoolSize(5); // 核心线程数调至5
executor.setMaximumPoolSize(20); // 最大线程数调至20
源码中是这么做的
public void setCorePoolSize(int corePoolSize) {
if (corePoolSize < 0 || maximumPoolSize < corePoolSize)
throw new IllegalArgumentException();
int delta = corePoolSize - this.corePoolSize;
this.corePoolSize = corePoolSize;
if (workerCountOf(ctl.get()) > corePoolSize)
interruptIdleWorkers();
else if (delta > 0) {
// We don't really know how many new threads are "needed".
// As a heuristic, prestart enough new workers (up to new
// core size) to handle the current number of tasks in
// queue, but stop if queue becomes empty while doing so.
int k = Math.min(delta, workQueue.size());
while (k-- > 0 && addWorker(null, true)) {
if (workQueue.isEmpty())
break;
}
}
}
/****************
安全算法
****************/
- 开启TLS
- SHA256
- 上下文反序列化过滤器
- 强封装内部API: 默认禁止反射访问JDK内部API
- 细粒度策略文件: 支持动态策略加载和条件化权限控制 ,应用层配置保护。
/****************
JDK 17中的性能优化
****************/
1、垃圾收集器优化: JDK 17继续优化了G1、ZGC等垃圾收集器,减少了垃圾回收的停顿时间。
2、JIT编译器改进: 通过改进即时编译器(JIT),提高了应用执行的速度和效率。
3、类加载性能提升: 优化了类加载过程,减少了应用启动和运行时的延迟。 <- 对CPU和内存都有优化。
4、应用启动时间优化: 通过改进JVM启动参数和运行时环境,缩短了应用的启动时间。
5、优化了内存管理: 改进了内存分配和管理机制,提高了内存使用效率。
反射受益:反射 API(如 Class.forName())的类查找耗时降低 35%。
/****************
JIT Just-In-Time compiler/即时编译器
****************/
Java虚拟机(JVM)中的C1/C2编译器,通过热点代码优化(如内联、循环展开)减少解释执行开销。
动态编译技术根据代码执行频率选择性优化,平衡编译速度与程序性
// CPU 上有优化
// 优化前:多次方法调用
int sum = 0;
for (int i = 0; i < 1000; i++) {
sum += getSquare(i); // 每次调用需创建栈帧
}
// 优化后:内联展开
int sum = 0;
for (int i = 0; i < 1000; i++) {
sum += i * i; // 消除方法调用开销
}
//内存上有优化
栈上分配:若对象未逃逸出方法,直接在栈上分配内存,减少堆分配和 GC 压力。
锁消除:对线程局部的对象同步操作,自动移除无竞争的锁(如局部 StringBuffer)
/****************
ZGC
****************/
全称:Garbage-First Garbage Collector(垃圾优先收集器)
核心目标:在保证高吞吐量的同时,实现可预测的低停顿时间(Soft Real-Time),尤其适合大内存(数十GB以上)和多核处理器环境。
取代地位:自 JDK 9 起成为 HotSpot 虚拟机默认垃圾收集器,全面替代 CMS(Concurrent Mark-Sweep
-XX:+UseG1GC
-XX:MaxGCPauseMillis=200 # 目标停顿时间
-XX:G1HeapRegionSize=4m # Region 大小(1-32MB)
-XX:InitiatingHeapOccupancyPercent=40 # 更早触发并发标记
-XX:G1ReservePercent=15 # 增加预留空间防复制失败3,9
/****************
ZGC
****************/
在ParallelOldGC、CMS和G1之后,JDK 11引入了全新的ZGC(Z Garbage Collector)。
一般很难了解ZGC改进有
###重点,JDK 17 对 ZGC 和 G1 GC 进行了显著改进,特别适合 Spark 的大内存和低延迟场景:
ZGC(Z Garbage Collector)
支持 TB 级堆内存下保持亚毫秒级停顿(通常 <10ms),避免 Full GC 导致的分钟级卡顿。
通过染色指针(Colored Pointers) 和并发压缩技术,减少内存碎片问题,提升 Spark Shuffle 和缓存数据的稳定性。
堆外内存控制
JDK 17 优化了 MaxDirectMemorySize 的默认行为,减少 Spark 因堆外内存溢出(如 java.lang.OutOfMemoryError: Direct buffer memory)导致的失败。
统一内存池
Spark 的 Off-Heap 内存(用于 Shuffle、缓存)与 JDK 17 的 Native Memory Tracking(NMT) 集成,便于监控和调优。
###好文,好参数
优化方向 JDK 17 特性 Spark 配置建议
垃圾回收 启用 ZGC(亚毫秒停顿) --conf spark.executor.extraJavaOptions=“-XX:+UseZGC”
向量化计算 Vector API 或 Gluten-Velox 使用 Spark 3.4+ 并集成 Gluten 插件
内存管理 监控 NMT + 调整堆外内存 spark.memory.offHeap.enabled=true
版本兼容性 优先选择 LTS 版本 升级至 Spark 3.3+(官方支持 JDK 17)
/****************
jshell
****************/
无用的功能,无法像python Django 一样交互
也不如scala
1309

被折叠的 条评论
为什么被折叠?



