Introduction to new features of Java 12, come and make up

Java 12 was released as early as March 19, 2019. It is not a long-term support (LTS) version. Before that, we have introduced the new features of other versions. If necessary, you can click the link below to read it.

Switch expression (JEP 325)

In Java 12, the writing method of switch expression is improved. Although it is an improvement of syntax sugar, it also makes the coding of switch more elegant. Let's take a look at the writing of switch before Java 12.

// 通过传入月份,输出月份所属的季节
public static void switchJava12Before(String day) {
    switch (day) {
        case "march":
        case "april":
        case "may":
            System.out.println("春天");
            break;
        case "june":
        case "july":
        case "august":
            System.out.println("夏天");
            break;
        case "september":
        case "october":
        case "november":
            System.out.println("秋天");
            break;
        case "december":
        case "january":
        case "february":
            System.out.println("冬天");
            break;
    }
}

In the above example, the season corresponding to a month is output by passing in a month. A lot of code is written for simple functions, and each operation needs a break to prevent case penetration.

Use preview function

Because the switch expression is not a officially released function in Java 12 and is still in the preview test stage, you need to open the function preview parameter if you want to use Java 12 to compile and run. Of course, if you use Java 14 or later, you can skip this part directly.

# 编译时
./bin/javac --enable-preview -source 12 ./Xxx.java
# 运行时
./bin/java --enable-preview Xxx

If a new feature is a preview function, it means that this function may be deleted in future versions.

Java 12 Switch

Due to the above problems of the switch, the switch is improved in Java 12 so that it can be operated in the way of case L - > so how can this code be written in Java 12?

public static void switchJava12(String day) {
    switch (day) {
        case "march","april","may"            -> System.out.println("春天");
        case "june","july","august"           -> System.out.println("夏天");
        case "september","october","november" -> System.out.println("秋天");
        case "december","january","february"  -> System.out.println("冬天");
    }
}

The expected output results can be obtained through the test. This is not enough. In the improvement of switch, it also supports assignment using the return value of switch.

Like this:

String season = switch (day) {
    case "march","may"            -> "春天";
    case "june","august"           -> "春天";
    case "september","november" -> "春天";
    case "december","february"  -> "春天";
    default -> {
    		//throw new RuntimeException("day error")
        System.out.println("day error");
        break "day error";
    }
};
System.out.println("当前季节是:" + season);

Although the writing is simpler, in fact, these are just syntax sugar updates. There is no big difference between compiled and before.

File comparison files mismatch

In Java, the operation of files has been enhanced in Java 7. This time, Java 12 brings the file comparison function. Comparing two files, if the contents are consistent, it will return - 1. If the contents are different, it will return different byte start positions.

// 创建两个文件
Path pathA = Files.createFile(Paths.get("a.txt"));
Path pathB = Files.createFile(Paths.get("b.txt"));

// 写入相同内容
Files.write(pathA,"abc".getBytes(),StandardOpenOption.WRITE);
Files.write(pathB,StandardOpenOption.WRITE);
long mismatch = Files.mismatch(pathA,pathB);
System.out.println(mismatch);

// 追加不同内容
Files.write(pathA,"123".getBytes(),StandardOpenOption.APPEND);
Files.write(pathB,"321".getBytes(),StandardOpenOption.APPEND);
mismatch = Files.mismatch(pathA,pathB);
System.out.println(mismatch);

// 删除创建的文件
pathA.toFile().deleteOnExit();
pathB.toFile().deleteOnExit();

// RESULT
// -1
// 3

The implementation of the comparison function can directly read the source code, which is still very simple.

Compact Number

The simplified digital format can directly convert the digital display format, such as 1000 - > 1K, 1000000 - > 1m.

System.out.println("Compact Formatting is:");
NumberFormat upVotes = NumberFormat.getCompactNumberInstance(new Locale("en","US"),Style.SHORT);

System.out.println(upVotes.format(100));
System.out.println(upVotes.format(1000));
System.out.println(upVotes.format(10000));
System.out.println(upVotes.format(100000));
System.out.println(upVotes.format(1000000));

// 设置小数位数
upVotes.setMaximumFractionDigits(1);
System.out.println(upVotes.format(1234));
System.out.println(upVotes.format(123456));
System.out.println(upVotes.format(12345678));

The output can be as follows:

100
1K
10K
100K
1M
1.2K
123.5K
12.3M

JVM related updates

Shenandoah garbage collector

Java 12 adds Shenandoah a low pause garbage collector, which can be carried out simultaneously with the execution threads in Java applications to collect garbage for content recycling, so as to reduce the pause time.

For more information about the Shenandoah garbage collector, see the document: Shenandoah GC introduction.

ZGC concurrent class unloading

Z garbage collector now supports class unloading, which releases the data structures related to these classes by unloading unused classes, thus reducing the overall space occupied by the application. Because it is executed concurrently, the execution of the Java application thread will not be stopped, so it has little impact on the pause time of GC. This feature is enabled by default, but - XX: - classunloading can be disabled using the command line option.

JVM constant API

In package Java lang.invoke. Constant defines a series of value based symbolic references that can be used to describe various loadable constants. It is easier to model the nominal descriptions of key class files and runtime builds, especially those loaded from the constant pool. It also allows developers to deal with loadable constants in a simpler and standard way.

Default use class data sharing (CDS)

This is not the first time JDK has improved CDs (class data sharing) function. CDS can greatly increase the speed of the JVM starting multiple applications on the same machine or virtual machine. The principle is to share some class loading information when starting applications, so that the shared data can be used when starting new processes. Before Java 12, this function needs to be turned on manually, and Java 12 is adjusted to be turned on by default.

Micro benchmark Kit

Add a new jmh based basic micro benchmark suite to Java 12. The use of jmh has also been introduced before. You can refer to the previous article jmh - the ultimate tool for Java code performance testing.

Other updates

1. Support Unicode 11

After Java 11 supports Unicode 10, Java 12 supports Unicode 11 and supports the operation of more emoticons and symbols.

reference resources

[1] http://openjdk.java.net/projects/jdk/12/

[2] https://wiki.openjdk.java.net/display/shenandoah/Main

[3] http://unicode.org/versions/Unicode11.0.0/

subscribe

You can follow my blog or wechat to search "unread code".

Articles will be updated in the same way as blogs and official account numbers.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>