woshikid / blog

Apache License 2.0
8 stars 1 forks source link

Java21新特性 #201

Open woshikid opened 3 months ago

woshikid commented 3 months ago

有序集合

ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.addFirst(1); // getFirst(), removeFirst()
arrayList.addLast(2); // getLast(), removeLast()
List<Integer> reversed = arrayList.reversed();
Collections.unmodifiableSequencedCollection(arrayList);
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.addFirst(1); // getFirst(), removeFirst()
linkedHashSet.addLast(2); // getLast(), removeLast()
SequencedSet<Integer> reversed = linkedHashSet.reversed();
Collections.unmodifiableSequencedSet(linkedHashSet);
LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.putFirst(1, "One"); // firstEntry(), pollFirstEntry()
linkedHashMap.putLast(2, "Two"); // lastEntry(), pollLastEntry()
SequencedMap<Integer, String> reversed = linkedHashMap.reversed();
SequencedSet<Integer> keySet = linkedHashMap.sequencedKeySet();
SequencedCollection<String> values = linkedHashMap.sequencedValues();
SequencedSet<Map.Entry<Integer, String>> entrySet = linkedHashMap.sequencedEntrySet();
Collections.unmodifiableSequencedMap(linkedHashMap);

分代ZGC

// 默认垃圾收集器仍为G1
java -XX:+UseZGC -XX:+ZGenerational // 启用分代ZGC

Record模式

public record Point(int x, int y) {}
Object obj = new Point(1, 2);
if (obj instanceof Point(int x, var y)) { // record可嵌套
    System.out.println(x+y);
}

switch模式匹配

switch (str) {
    case null -> {} // 默认抛出NullPointerException
    case "y", "Y" -> System.out.println("Yes");
    case "n", "N" -> System.out.println("No");
    case String s when s.equals("yes") -> System.out.println("Yes");
    case String s when s.equals("no") -> System.out.println("No");
    case String s -> System.out.println("Other");
}
switch (obj) {
    case null -> System.out.println(); // 默认抛出NullPointerException
    case String s when s.equals("one") -> System.out.println("one");
    case String s -> System.out.println("many");
    case Integer i -> System.out.println("int");
    case Point(var x, int y) -> System.out.println(x+y);
    default -> {}
}

虚拟线程

对于CPU密集型任务,效果等同于Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()) 注意:使用synchronizednative将使该虚拟线程独占一个平台线程从而导致阻塞,使用-Djdk.tracePinnedThreads=short以跟踪该阻塞

Thread.startVirtualThread(() -> System.out.println("job")); // isVirtual(), isDaemon()
Thread.ofVirtual().start(() -> System.out.println("job"));
Thread.ofVirtual().unstarted(() -> System.out.println("job")).start();
Thread.ofVirtual().factory().newThread(() -> System.out.println("job")).start();
//Thread.ofPlatform().start(() -> System.out.println("platform"));
//Thread.getAllStackTraces(); // 获得所有平台线程
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
executor.submit(() -> "job");

导出虚拟线程快照

jcmd <PID> Thread.dump_to_file -format=json dump.json