Java 12功能

Finally, JDK 12 which is a part of the six-month release cycle, is here. It comes after the last Java LTS version 11. We had discussed at length on Java 11 features before. Today we’ll be discussing Java 12 features and see what it has in store for developers.

最后,这是六个月发布周期的一部分,JDK 12在这里。 它是在上一个Java LTS版本11之后发布的。之前我们已经详细讨论过Java 11功能 。 今天,我们将讨论Java 12功能,并为开发人员了解它的功能。

Java 12 was launched on March 19, 2019. It is a Non-LTS version. Hence it won’t have long term support.

Java 12于2019年3月19日发布。它是Non-LTS版本。 因此,它将不会有长期的支持。

Java 12功能 (Java 12 Features)

Some of the important Java 12 features are;

Java 12的一些重要功能是:

  1. JVM Changes – JEP 189, JEP 346, JEP 344, and JEP 230.

    JVM更改– JEP 189,JEP 346,JEP 344和JEP 230。
  2. Switch Expressions

    切换表达式
  3. File mismatch() Method

    文件不匹配()方法
  4. Compact Number Formatting

    紧凑数字格式
  5. Teeing Collectors in Stream API

    在Stream API中准备收集器
  6. Java Strings New Methods – indent(), transform(), describeConstable(), and resolveConstantDesc().

    Java字符串新方法– indent(),transform(),describeConstable()和resolveConstantDesc()。
  7. JEP 334: JVM Constants API

    JEP 334:JVM常量API
  8. JEP 305: Pattern Matching for instanceof

    JEP 305:用于instanceof的模式匹配
  9. Raw String Literals is Removed From JDK 12.

    从JDK 12中删除了原始字符串文字。

Let’s look into all these Java 12 features one by one.

让我们逐一研究所有这些Java 12功能。

JVM更改 (JVM Changes)

1. JEP 189 –雪兰多厄:低暂停时间的垃圾收集器(实验性) (1. JEP 189 – Shenandoah: A Low-Pause-Time Garbage Collector (Experimental))

RedHat initiated Shenandoah Garbage Collector to reduce GC pause times. The idea is to run GC concurrently with the running Java threads.

RedHat启动了Shenandoah垃圾收集器以减少GC暂停时间。 这个想法是与运行中的Java线程同时运行GC。

It aims at consistent and predictable short pauses irrelevant of the heap size. So it does not matter if the heap size is 15 MB or 15GB.

它旨在与堆大小无关的一致且可预测的短暂停顿。 因此,堆大小是15 MB还是15GB都没有关系。

It is an experimental feature in Java 12.

它是Java 12中的一项实验性功能。

2. JEP 346 –立即从G1返回未使用的承诺内存 (2. JEP 346 – Promptly Return Unused Committed Memory from G1)

Stating Java 12, G1 will now check Java Heap memory during inactivity of application and return it to the operating system. This is a preemptive measure to conserve and use free memory.

说明Java 12,G1现在将在应用程序不活动期间检查Java堆内存,并将其返回给操作系统。 这是保存和使用可用内存的先发措施。

3. JEP 344:G1的可终止混合集合 (3. JEP 344 : Abortable Mixed Collections for G1)

Improvements in G1 efficiency include making G1 mixed collections abortable if they might exceed the defined pause target. This is done by splitting the mixed collection set into mandatory and optional.
Thus the G1 collector can prioritize on collecting the mandatory set first to meet the pause time goal.

G1效率的提高包括:如果G1混合集合可能超出定义的暂停目标,则可以将其中止。 这是通过将混合集合集分为强制和可选来完成的。
因此,G1收集器可以优先考虑首先收集强制性集合,以满足暂停时间目标。

4. JEP 230和344 (4. JEP 230 and 344)

Microbenchmark Suite, JEP 230 feature adds a basic suite of microbenchmarks to the JDK source code. This makes it easy for developers to run existing microbenchmarks and create new ones.

Microbenchmark Suite,JEP 230功能向JDK源代码添加了基本的microbenchmark套件。 这使开发人员可以轻松地运行现有的微基准并创建新的微基准。

One AArch64 Port, Not Two, JEP 344, removes all of the sources related to the arm64 port while retaining the 32-bit ARM port and the 64-bit aarch64 port. This allows contributors to focus their efforts on a single 64-bit ARM implementation

一个AArch64端口(不是两个),JEP 344删除了与arm64端口相关的所有源,同时保留了32位ARM端口和64位aarch64端口。 这使贡献者可以将精力集中在单个64位ARM实现上。

5. JEP 341默认CDS存档 (5. JEP 341 Default CDS Archives)

This enhances the JDK build process to generate a class data-sharing (CDS) archive, using the default class list, on 64-bit platforms. The goal is to improve startup time. From Java 12, CDS is by default ON.

这增强了JDK生成过程,以在64位平台上使用默认的类列表生成类数据共享(CDS)存档。 目标是缩短启动时间。 从Java 12开始,默认情况下CDS为ON。

To run your program with CDS turned off do the following:

要在CDS关闭的情况下运行程序,请执行以下操作:

java -Xshare:off HelloWorld.java

Now, this would delay the startup time of the program.

现在,这将延迟程序的启动时间。

语言更改和功能 (Language Changes And Features)

Java 12 has introduced many language features. Let us look at a few with implementations.

Java 12引入了许多语言功能。 让我们来看一些实现。

1.切换表达式(预览) (1. Switch Expressions (Preview))

Java 12 has enhanced Switch expressions for Pattern matching.
Introduced in JEP 325, as a preview language feature, the new Syntax is L ->.

Java 12增强了用于模式匹配的Switch表达式。
作为预览语言功能,在JEP 325中引入,新的语法为L ->

Following are some things to note about Switch Expressions:

以下是有关开关表达式的一些注意事项:

  • The new Syntax removes the need for break statement to prevent fallthroughs.

    新的语法消除了对break语句的需要,以防止失败。
  • Switch Expressions don’t fall through anymore.

    开关表达式不再适用。
  • Furthermore, we can define multiple constants in the same label.

    此外,我们可以在同一标签中定义多个常量。
  • default case is now compulsory in Switch Expressions.

    现在,“ default表达式”在“开关表达式”中是必需的。
  • break is used in Switch Expressions to return values from a case itself.

    开关表达式中使用break来从案例本身返回值。

Classic switch statement:

经典切换语句:

String result = "";
        switch (day) {
            case "M":
            case "W":
            case "F": {
                result = "MWF";
                break;
            }
            case "T":
            case "TH":
            case "S": {
                result = "TTS";
                break;
            }
        };

        System.out.println("Old Switch Result:");
        System.out.println(result);

With the new Switch expression, we don’t need to set break everywhere thus prevent logic errors!

使用新的Switch表达式,我们无需到处设置中断,从而避免了逻辑错误!

String result = switch (day) {
            case "M", "W", "F" -> "MWF";
            case "T", "TH", "S" -> "TTS";
            default -> {
                if(day.isEmpty())
                    break "Please insert a valid day.";
                else
                    break "Looks like a Sunday.";
            }

        };

        System.out.println(result);

Let’s run the below program containing the new Switch Expression using JDK 12.

让我们使用JDK 12运行下面的程序,其中包含新的Switch Expression。

public class SwitchExpressions {

    public static void main(String[] args)
    {
        System.out.println("New Switch Expression result:");
        executeNewSwitchExpression("M");
        executeNewSwitchExpression("TH");
        executeNewSwitchExpression("");
        executeNewSwitchExpression("SUN");
    }

    public static void executeNewSwitchExpression(String day){

        String result = switch (day) {
            case "M", "W", "F" -> "MWF";
            case "T", "TH", "S" -> "TTS";
            default -> {
                if(day.isEmpty())
                    break "Please insert a valid day.";
                else
                    break "Looks like a Sunday.";
            }

        };

        System.out.println(result);
    }
}

Since this is a preview feature, please ensure that you have selected the Language Level as Java 12 preview.
To compile the above code run the following command:

由于这是预览功能,因此请确保已选择“语言级别”作为Java 12预览。
要编译以上代码,请运行以下命令:

javac -Xlint:preview --enable-preview -source 12 src/main/java/SwitchExpressions.java

After running the compiled program, we get the following in the console

运行编译的程序后,我们在控制台中获得以下内容

Java 12功能_第1张图片

Java Switch Expressions Program Output

Java开关表达式程序输出

preview language feature. This means that even though it is complete, it may not be confirmed in the future Java Release. 预览语言功能 。 这意味着,即使它已完成,也可能无法在将来的Java版本中得到确认。

2. File.mismatch方法 (2. File.mismatch method)

Java 12 added the following method to compare two files:

Java 12添加了以下方法来比较两个文件:

public static long mismatch(Path path, Path path2) throws IOException

This method returns the position of the first mismatch or -1L if there is no mismatch.

此方法返回第一个不匹配的位置;如果没有不匹配,则返回-1L。

Two files can have a mismatch in the following scenarios:

在以下情况下,两个文件可能不匹配:

  • If the bytes are not identical. In this case, the position of the first mismatching byte is returned.

    如果字节不相同。 在这种情况下,将返回第一个不匹配字节的位置。
  • File sizes are not identical. In this case, the size of the smaller file is returned.

    文件大小不相同。 在这种情况下,将返回较小文件的大小。

Example code snippet from IntelliJ Idea is given below:

下面给出了IntelliJ Idea的示例代码片段:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class FileMismatchExample {

    public static void main(String[] args) throws IOException {
        Path filePath1 = Files.createTempFile("file1", ".txt");
        Path filePath2 = Files.createTempFile("file2", ".txt");
        Files.writeString(filePath1,"JournalDev Test String");
        Files.writeString(filePath2,"JournalDev Test String");

        long mismatch = Files.mismatch(filePath1, filePath2);

        System.out.println("File Mismatch position... It returns -1 if there is no mismatch");

        System.out.println("Mismatch position in file1 and file2 is >>>>");
        System.out.println(mismatch);

        filePath1.toFile().deleteOnExit();
        filePath2.toFile().deleteOnExit();

        System.out.println();

        Path filePath3 = Files.createTempFile("file3", ".txt");
        Path filePath4 = Files.createTempFile("file4", ".txt");
        Files.writeString(filePath3,"JournalDev Test String");
        Files.writeString(filePath4,"JournalDev.com Test String");

        long mismatch2 = Files.mismatch(filePath3, filePath4);

        System.out.println("Mismatch position in file3 and file4 is >>>>");
        System.out.println(mismatch2);

        filePath3.toFile().deleteOnExit();
        filePath4.toFile().deleteOnExit();



    }

}

The output when the above Java Program is compiled and run is:

编译并运行上述Java程序时,输出为:

Java 12功能_第2张图片

Java File Mismatch Example Program Output

Java文件不匹配示例程序输出

3.紧凑的数字格式 (3. Compact Number Formatting)

import java.text.NumberFormat;
import java.util.Locale;

public class CompactNumberFormatting {


    public static void main(String[] args)
    {
        System.out.println("Compact Formatting is:");
        NumberFormat upvotes = NumberFormat
                .getCompactNumberInstance(new Locale("en", "US"), NumberFormat.Style.SHORT);
        upvotes.setMaximumFractionDigits(1);

        System.out.println(upvotes.format(2592) + " upvotes");


        NumberFormat upvotes2 = NumberFormat
                .getCompactNumberInstance(new Locale("en", "US"), NumberFormat.Style.LONG);
        upvotes2.setMaximumFractionDigits(2);
        System.out.println(upvotes2.format(2011) + " upvotes");
    }


}
Java Compact Number Formatting Program Output

Java Compact Number Formatting Program Output

Java Compact Number格式化程序输出

4.发球收藏家 (4. Teeing Collectors)

Teeing Collector is the new collector utility introduced in the Streams API.

Teeing Collector是Streams API中引入的新的收集器实用程序。

This collector has three arguments – Two collectors and a Bi-function.
All input values are passed to each collector and the result is available in the Bi-function.

该收集器具有三个参数–两个收集器和一个Bi函数。
所有输入值都传递到每个收集器,结果在Bi功能中可用。

double mean = Stream.of(1, 2, 3, 4, 5)
                .collect(Collectors.teeing(
                        summingDouble(i -> i),
                        counting(),
                        (sum, n) -> sum / n));

System.out.println(mean);

The output is 3.0.

输出为3.0

5. Java字符串新方法 (5. Java Strings New Methods)

4 new methods have been introduced in Java 12 which are:

Java 12中引入了4种新方法,它们是:

  • indent(int n)

    缩进(int n)
  • transform(Function super String,​? extends R> f)

    transform(函数super String,??扩展R> f)
  • Optional describeConstable()

    可选的 describeConstable()
  • String resolveConstantDesc​(MethodHandles.Lookup lookup)

    字符串resolveConstantDesc((MethodHandles.Lookup查找)

To know about the above methods and there implementation in detail, refer to our Java 12 String Methods tutorial.

要了解上述方法及其详细实现,请参阅我们的Java 12 String Methods教程。

6. JEP 334:JVM常量API (6. JEP 334: JVM Constants API)

A new package java.lang.constant is introduced with this JEP. This is not that useful for those developers who don’t use constants pool.

该JEP引入了新的包java.lang.constant 。 对于不使用常量池的开发人员来说,这没什么用。

7. JEP 305:instanceof的模式匹配(预览) (7. JEP 305: Pattern Matching for instanceof (Preview))

Another Preview Language feature!

另一个预览语言功能!

The old way to typecast a type to another type is:

将一个类型转换为另一种类型的旧方法是:

if (obj instanceof String) {
    String s = (String) obj;
    // use s in your code from here
}

The new way is :

新方法是:

if (obj instanceof String s) {
    // can use s directly here
}

This saves us some typecasting which were unnecessary.

这为我们节省了一些不必要的类型转换。

Raw String Literals is Removed From JDK 12.
从JDK 12中删除了原始字符串文字。

That brings an end to this article on Java 12 features.

这结束了有关Java 12功能的本文。

翻译自: https://www.journaldev.com/28666/java-12-features

你可能感兴趣的:(字符串,java,python,jvm,jdk)