New features of Java12

  java, jdk12

Java language feature series


This article focuses on the new features of Java12

Version number

java -version
openjdk version "12" 2019-03-19
OpenJDK Runtime Environment (build 12+33)
OpenJDK 64-Bit Server VM (build 12+33, mixed mode)

From the version information, it can be seen that build 12+33

Property list

Shenandoah GC is a low-pause-time oriented garbage collector. It was originally implemented by Red Hat and supports aarch64 and amd64 architecture;. ZGC is also a garbage collector for low-pause-time, but ZGC is implemented based on colored pointers, while Shenandoah GC is implemented based on brooks pointers. If you want to use shenandoahgc, you need to compile-with –with-jvm-features option with Shenandoah GC, and then use-xx:+unlockxperimentalvmoptions-xx:+useshenandoah GC at startup

A basic microbenchmarks suite has been added to the jdk source code.

Switch has been enhanced. In addition to statement, expression can be used. For example, the original wording is as follows:

switch (day) {
    case MONDAY:
    case FRIDAY:
    case SUNDAY:
    case TUESDAY:
    case THURSDAY:
    case SATURDAY:
    case WEDNESDAY:

Now it can be changed to read as follows:

switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
    case TUESDAY                -> System.out.println(7);
    case THURSDAY, SATURDAY     -> System.out.println(8);
    case WEDNESDAY              -> System.out.println(9);

And return value in expression

int numLetters = switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> 6;
    case TUESDAY                -> 7;
    case THURSDAY, SATURDAY     -> 8;
    case WEDNESDAY              -> 9;

For switch expression that needs to return a value, either return a normal value or throw an exception, the following two methods are wrong

int i = switch (day) {
    case MONDAY -> {
        // ERROR! Block doesn't contain a break with value
    default -> 1;
i = switch (day) {
        break 0;
        System.out.println("Second half of the week");
        // ERROR! Group doesn't contain a break with value

JVM Constants API has been added, specifically java.base module has added java.lang.constant package and introduced ConstantDesc interface (ClassDesc, MethodTypeDesc, MethodHandleDesc directly inherit ConstantDesc interface) and Constable interface; The ConstantDesc interface defines the resolveConstantDesc method, and the Constable interface defines the describeConstable method. String, Integer, Long, Float, Double all implement these two interfaces, while EnumDesc implements ConstantDesc interface.

64-bit Arm platform (arm64), which can also be called aarch64;; JDK has two previous implementations of ARCH 64, namely src/hotspot/cpu/arm and Open/SRC/Hotspot/CPU/ARCH 64. Their implementations are repeated. In order to concentrate on better implementing ARCH 64, this feature deletes the 64-bit implementation in open/src/hotspot/cpu/arm in the source code. The 32-bit implementation is retained, so the open/src/hotspot/CPU/arcach64 part becomes the default implementation of 64-bit ARM architecture.

New features of java10JEP 310: Application Class-Data SharingExtended the Class-Data Sharing introduced by JDK5 and supported the class-data sharing of application; Class-Data Sharing can be used to share Class among multiple JVMs to improve startup speed. At the earliest, it only supports system classes and serial GC. JDK9 extended it to support application classes and other GC algorithms, and it was opened up in JDK10 (Previously, it was a commercial feature.); JDK11 changed -Xshare:off to the default -Xshare:auto to make it easier to use CDS features; This feature of jdk12 defaults to &dollar when compiling JDK on 64-bit platform. {JAVA_HOME}/lib/server directory generates a default archive file named classes.jsa (About 18M) is convenient for everyone to use.

When G1 is in garbage collection, once the collection set (CSet) The process of starting garbage collection is without stopping. When the collection set is too large, the STW time at this time will exceed the target pause time too long, which is more obvious in mixed collections. This feature starts a mechanism that allows a relatively large collection set to be divided into two parts: mandatory and optional (When the mandatory part is completed, the optional part will be processed if there is still time left.) to change mixed collections from without stopping to abortable to better meet the target of the specified pause time

G1 will only return memory at full GC or concurrent cycle at present. since G1 tries to avoid both scenarios, it may not return the committed Java heap memory to the operating system in time in most scenarios. Two new parameters are added to this feature of JDK12: G1PeriodicGCInterval and G1 PeriodicgSystemLoadThreshold. If it is set to 0, it is disabled. Last garbage collection pause Past G1PeriodicGCInterval (millisecondsIf getloadavg () (one-minute) is lower than the threshold specified by G1 PeriodicSystemLoadThreshold, then full GC or concurrent GC (If G1PeriodicGCInvokesConcurrent is turned on), Java heap size will be rewritten and adjusted after GC, and then excess memory will be returned to the operating system.

Detailed interpretation

The features listed above are in many aspects. Besides, there are also some api updates and discards. SeeJDK 12 Release NotesHere are a few examples.

Add item

  • Unicode 11 support
  • Compact Number Formatting is supported.

Examples are as follows

    public void testCompactNumberFormat(){
        var cnf = NumberFormat.getCompactNumberInstance(Locale.CHINA, NumberFormat.Style.SHORT);
        System.out.println(cnf.format(1L << 30));
        System.out.println(cnf.format(1L << 40));
        System.out.println(cnf.format(1L << 50));


  • String supports transform and indent operations.
    public void testStringTransform(){
        System.out.println("hello".transform(new Function<String, Integer>() {
            public Integer apply(String s) {
                return s.hashCode();

    public void testStringIndent(){
  • Files adds a mismatch method.
    public void testFilesMismatch() throws IOException {
        FileWriter fileWriter = new FileWriter("/tmp/a.txt");

        FileWriter fileWriterB = new FileWriter("/tmp/b.txt");

  • Collectors add the teeing method to aggregate the results of two downstream
    public void testCollectorTeeing(){
        var result = Stream.of("Devoxx","Voxxed Days","Code One","Basel One")
                .collect(Collectors.teeing(Collectors.filtering(n -> n.contains("xx"),Collectors.toList()),
                                            Collectors.filtering(n -> n.endsWith("One"),Collectors.toList()),
                        (List<String> list1, List<String> list2) -> List.of(list1,list2)

  • CompletionStage Adds exceptionallyAsync, exceptionallyCompose, exceptionallyComposeAsync Methods
    public void testExceptionallyAsync() throws ExecutionException, InterruptedException {"begin");
        int result = CompletableFuture.supplyAsync(() -> {
            int i = 1/0;
            return 100;
        }).exceptionallyAsync((t) -> {
  "error error:{}",t.getMessage());
            return 0;
  • Before JDK12, the CompletionStage has only one exception, which is executed in the main thread. JDK12 has added the exceptionallyAsync and exceptionallyComposeAsync methods to allow the execution of the metho d in the asynchronous thread, while adding the exception component method to support the construction of a new CompletionStage when exception occurs.
  • Allocation of Old Generation of Java Heap on Alternate Memory Devices

G1 and Parallel GC introduce the experimental feature, allowing old generation to be assigned to alternative memory device such as nv-dimmemory.

  • ZGC: Concurrent Class Unloading

ZGC did not support class unloading when JDK11. JDK12 supports Concurrent Class Unloading for ZGC, which is turned on by default and can be disabled by using -XX:-ClassUnloading.

  • Add -XX:+ExtensiveErrorReports

-xx:+extensiveerrorreport can be used to collect more report information into hs_err<pid>.log file when jvm crash. the default is closed in productbuildings. to open it, you need to add-xx:+extensiveerrorreport parameter yourself

  • Add safety-related improvements

Support system properties. When set to disallow, SecurityManager is not used to improve performance. If System.setSecurityManager is called at this time, UnsupportedOperationException will be thrown.
The keytool add -groupname option allows you to specify a named group when generating key pair.
The new PKCS12 KeyStore configuration attribute is used to customize PKCS12 keystores generation.
Java Flight Recorder added a security-related event.
Support for chachacha20 and poly1305 tlscuppers

  • jdeps Reports Transitive Dependences

Jdeps’s-print-module-deps,-list-deps, and-list-reduce-deps options have been enhanced, adding-no-recurrent for non-transitive dependency analysis, –ignore-missing-deps-deps for suppressmissing dependencies errors

Remove item

  • Remove com.sun.awt.SecurityWarnin
  • Finalize method to remove FileInputStream, FileOutputStream, Java.util.ZipFile/Inflator/Deflator
  • Remove gtechybertrust globalroot
  • Remove javac’s -source, -target support for 6 and 1.6 while removing the –release option

Abandoned item

  • See for a list of abandoned apis.deprecated-list
  • Obsolete-xx:+/-XX:+/-MonitorInUseLists option
  • Discard the -keyalg value of Default Keytool

Known problem

  • Swing does not support GTK+ 3.20 and later
  • When using JVMCI Compiler (For example, Graal) of JVMTI, the capabilities of can_pop_frame and can_force_early_return are disabled

any other business

  • If the user does not specify user.timezone and gets null from the operating system, the initial value of the user.timezone property is null and becomes null
  • The behavior of has slightly changed. before, it would ignore the query and fragment parts in the URL. this change adds the query and fragment parts, namelyscheme : // authority [ / path ]Change toscheme : // authority [ / path ] [ ignored-query-or-fragment ]
  • API and java security standard algorithms names specification remove the requirement to implement TLSv1 and TLSv1.1


  • Java12 is not LTS (Long-Term Support) version (LTS is only available in oracle version), oracle’s support cycle for this version is 6 months. This version mainly has several update points, one is syntax level update, one is API level update, and the other is GC level update.
  • The syntax level introduces the preview version of Switch Expressions; ; JVM Constants API is introduced at API level, CompactNumberFormat is introduced, NumberFormat supports COMPACTSTYLE, and new methods such as String, Files, Collectors and CompletionStage are added. The GC aspect has introduced the experimental version of Shenandoah GC, but oracle build’s openjdk does not have enableshenandoah gcsupport; In addition, ZGC and G1 GC are mainly improved
  • JDK12 supports Concurrent Class Unloading for ZGC, which is turned on by default and can be disabled by -XX:-ClassUnloading; For G1 GC, it adds the features supporting Abortable Mixed Collections and promptly returnunused committedmemory.