Java15的新特性

Java語言特性系列

本文主要講述一下Java15的新特性html

版本號

java -version
openjdk version "15" 2020-09-15
OpenJDK Runtime Environment (build 15+36-1562)
OpenJDK 64-Bit Server VM (build 15+36-1562, mixed mode, sharing)
從version信息能夠看出是build 15+36

特性列表

339:Edwards-Curve Digital Signature Algorithm (EdDSA)

新增 rfc8032描述的Edwards-Curve Digital Signature Algorithm (EdDSA)實現
使用示例
// example: generate a key pair and sign
KeyPairGenerator kpg = KeyPairGenerator.getInstance("Ed25519");
KeyPair kp = kpg.generateKeyPair();
// algorithm is pure Ed25519
Signature sig = Signature.getInstance("Ed25519");
sig.initSign(kp.getPrivate());
sig.update(msg);
byte[] s = sig.sign();

// example: use KeyFactory to contruct a public key
KeyFactory kf = KeyFactory.getInstance("EdDSA");
boolean xOdd = ...
BigInteger y = ...
NamedParameterSpec paramSpec = new NamedParameterSpec("Ed25519");
EdECPublicKeySpec pubSpec = new EdECPublicKeySpec(paramSpec, new EdPoint(xOdd, y));
PublicKey pubKey = kf.generatePublic(pubSpec);

360:Sealed Classes (Preview)

JDK15引入了sealed classes and interfaces.用於限定實現類,限定父類的使用,爲後續的pattern matching的exhaustive analysis提供便利
示例
package com.example.geometry;

public abstract sealed class Shape
    permits Circle, Rectangle, Square {...}

public final class Circle extends Shape {...}

public sealed class Rectangle extends Shape 
    permits TransparentRectangle, FilledRectangle {...}
public final class TransparentRectangle extends Rectangle {...}
public final class FilledRectangle extends Rectangle {...}

public non-sealed class Square extends Shape {...}
這裏使用了3個關鍵字,一個是sealed,一個是permits,一個是non-sealed;permits的這些子類要麼使用final,要麼使用sealed,要麼使用non-sealed修飾;針對record類型,也可使用sealed,由於record類型暗示這final
package com.example.expression;

public sealed interface Expr
    permits ConstantExpr, PlusExpr, TimesExpr, NegExpr {...}

public record ConstantExpr(int i)       implements Expr {...}
public record PlusExpr(Expr a, Expr b)  implements Expr {...}
public record TimesExpr(Expr a, Expr b) implements Expr {...}
public record NegExpr(Expr e)           implements Expr {...}

371:Hidden Classes

JDK15引入了Hidden Classes,同時廢棄了非標準的sun.misc.Unsafe::defineAnonymousClass,目標是爲frameworks提供在運行時生成內部的class

372:Remove the Nashorn JavaScript Engine

JDK15移除了Nashorn JavaScript Engine及jjs tool,它們在JDK11的被標記爲廢棄;具體就是jdk.scripting.nashorn及jdk.scripting.nashorn.shell這兩個模塊被移除了

373:Reimplement the Legacy DatagramSocket API

該特性使用更簡單及更現代的方式從新實現了java.net.DatagramSocket及java.net.MulticastSocket以方便更好的維護及debug,新的實現將會更容易支持virtual threads

374:Disable and Deprecate Biased Locking

該特性默認禁用了biased locking( -XX:+UseBiasedLocking),而且廢棄了全部相關的命令行選型( BiasedLockingStartupDelay, BiasedLockingBulkRebiasThreshold, BiasedLockingBulkRevokeThreshold, BiasedLockingDecayTime, UseOptoBiasInlining, PrintBiasedLockingStatistics and PrintPreciseBiasedLockingStatistics)

375:Pattern Matching for instanceof (Second Preview)

instanceof的Pattern Matching在JDK15進行Second Preview,示例以下:
public boolean equals(Object o) { 
    return (o instanceof CaseInsensitiveString cis) && 
        cis.s.equalsIgnoreCase(s); 
}

377:ZGC: A Scalable Low-Latency Garbage Collector

ZGC在JDK11被做爲experimental feature引入,在JDK15變成Production,可是這並非替換默認的GC,默認的GC仍然仍是G1;以前須要經過 -XX:+UnlockExperimentalVMOptions -XX:+UseZGC來啓用ZGC,如今只須要 -XX:+UseZGC就能夠
相關的參數有ZAllocationSpikeTolerance、ZCollectionInterval、ZFragmentationLimit、ZMarkStackSpaceLimit、ZProactive、ZUncommit、ZUncommitDelay
ZGC-specific JFR events( ZAllocationStall、ZPageAllocation、ZPageCacheFlush、ZRelocationSet、ZRelocationSetGroup、ZUncommit)也從experimental變爲product

378:Text Blocks

Text Blocks在JDK13被做爲preview feature引入,在JDK14做爲Second Preview,在JDK15變爲最終版

379:Shenandoah: A Low-Pause-Time Garbage Collector

Shenandoah在JDK12被做爲experimental引入,在JDK15變爲Production;以前須要經過 -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC來啓用,如今只須要 -XX:+UseShenandoahGC便可啓用

381:Remove the Solaris and SPARC Ports

Solaris and SPARC Ports在JDK14被標記爲廢棄,在JDK15版本正式移除

383:Foreign-Memory Access API (Second Incubator)

Foreign-Memory Access API在JDK14被做爲incubating API引入,在JDK15處於Second Incubator

384:Records (Second Preview)

Records在JDK14被做爲preview引入,在JDK15處於Second Preview

385:Deprecate RMI Activation for Removal

JDK15廢棄了RMI Activation,後續將被移除

細項解讀

上面列出的是大方面的特性,除此以外還有一些api的更新及廢棄,主要見JDK 15 Release Notes,這裏舉幾個例子。java

添加項

升級了Unicode,支持Unicode 13.0
  • Added isEmpty Default Method to CharSequence (JDK-8215401)
給CharSequence新增了isEmpty方法
java.base/java/lang/CharSequence.java
/**
     * Returns {@code true} if this character sequence is empty.
     *
     * @implSpec
     * The default implementation returns the result of calling {@code length() == 0}.
     *
     * @return {@code true} if {@link #length()} is {@code 0}, otherwise
     * {@code false}
     *
     * @since 15
     */
    default boolean isEmpty() {
        return this.length() == 0;
    }
  • Added Support for SO_INCOMING_NAPI_ID Support (JDK-8243099)
jdk.net.ExtendedSocketOptions新增了SO_INCOMING_NAPI_ID選型
  • Specialized Implementations of TreeMap Methods (JDK-8176894)
JDK15對TreeMap提供了putIfAbsent, computeIfAbsent, computeIfPresent, compute, merge方法提供了overriding實現
  • New Option Added to jcmd for Writing a gzipped Heap Dump (JDK-8237354)
jcmd的GC.heap_dump命令如今支持gz選型,以dump出gzip壓縮版的heap;compression level從1( fastest)到9( slowest, but best compression),默認爲1
  • New System Properties to Configure the TLS Signature Schemes (JDK-8242141)
新增了 jdk.tls.client.SignatureSchemesjdk.tls.server.SignatureSchemes用於配置TLS Signature Schemes
  • Support for certificate_authorities Extension (JDK-8206925)
支持certificate_authorities的擴展

移除項

淘汰了-XX:UseAdaptiveGCBoundary

廢棄項

廢棄了ForceNUMA選項
  • Disable Native SunEC Implementation by Default (JDK-8237219)
默認禁用了Native SunEC Implementation

已知問題

  • java.net.HttpClient Does Not Override Protocols Specified in SSLContext Default Parameters (JDK-8239594)
HttpClient如今沒有覆蓋在SSLContext Default Parameters中指定的Protocols

其餘事項

  • DatagramPacket.getPort() Returns 0 When the Port Is Not Set (JDK-8237890)
當DatagramPacket沒有設置port的時候,其getPort方法返回0
  • Improved Ergonomics for G1 Heap Region Size (JDK-8241670)
優化了默認G1 Heap Region Size的計算

小結

Java15主要有以下幾個特性git

doc

相關文章
相關標籤/搜索