java 1.8新增功能

    科技2022-08-01  119

    java 1.8新增功能

    Hello All, As a java developer we need to update our shelf about the new features, enhancement, or deprecated API of every new release of Java. JDK 14 comes plenty of new or previewing and Incubator features such as pattern matching for instanceof, Helpful NullPointerExceptions, switch expressions, Memory management API, deprecated some garbage collector algorithm, and many more.

    大家好,作为Java开发人员,我们需要更新有关每个Java新版本的新功能,增强功能或不推荐使用的API的信息。 JDK 14具有许多新功能或预览功能以及Incubator功能,例如模式匹配(例如instanceof),有用的NullPointerExceptions ,开关表达式,内存管理API,已弃用的某些垃圾收集器算法等等。

    In the Software industry, Java Developers are still using an older version of java like java8 or java7 or java6 or even older ones. Java8 has a major feature release and that is a lambda expression, Functional programming capability.

    在软件行业,Java开发人员仍在使用Java的较旧版本,例如java8或java7或java6,甚至更旧的版本。 Java8有一个主要功能版本,它是lambda表达式 ,即 功能编程 功能 。

    So whether we’re migrating over to Java9 or Java 11 or java13 or maybe even Java 14, Java 8 concepts and features are still very much alive in the JDK. Here, I would like to share the important changes, enhancements, removed APIs and features, deprecated APIs and features, and other information about JDK 14.

    因此,无论我们要迁移到Java9还是Java 11或java13甚至Java 14, Java 8的概念和功能在JDK中仍然非常活跃。 在这里,我想分享重要的更改,增强,已删除的API和功能,不推荐使用的API和功能以及有关JDK 14的其他信息。

    There are several categories of new, nonfinal features

    有几类新的非最终功能

    A preview language or VM feature is a new feature of the Java SE Platform that is fully specified, fully implemented, and yet impermanent. It is available in a JDK feature release to provoke developer feedback based on real-world use. To compile source code with javac that uses preview features from JDK release n, use javac from JDK release n with the --enable-preview command-line option in conjunction with either the --release n or -source n command-line option. javac — enable-preview — release 14 <JavaSourceCode.java>

    预览语言或VM功能是Java SE平台的一项新功能,该功能已完全指定,完全实现但不是永久性的。 JDK功能版本中提供了该功能,以根据实际使用情况激发开发人员反馈。 将源代码编译用javac使用预览从JDK释放N,使用javac特征从JDK释放n,其中的--enable-preview与任一结合命令行选项--release n或-source n命令行选项。 javac —启用预览—版本14 <JavaSourceCode.java>

    Experimental, mainly for new features in the HotSpot JVM

    实验性的,主要用于HotSpot JVM中的新功能

    Incubating (also known as incubator modules), for potentially new APIs and JDK tools. Incubating Features are experimental APIs distributed in a form of separate modules with names prefixed with “jdk.incubator.”

    潜在的新API和JDK工具的孵化(也称为孵化器模块)。 孵化功能是实验性API,以单独模块的形式分发,名称以“ jdk.incubator”为前缀。

    Here’s the list of some important and useful Java 14 features:

    以下是一些重要和有用的Java 14功能列表:

    1. instanceof的模式匹配(预览) (1. Pattern Matching for instanceof (Preview))

    An instanceof in Java is a comparison operator which, given an object instance, checks whether that instance is of a specified type (class/sub-class/interface) or not. Just like other comparison operators, it returns true or false.

    Java中的instanceof是一个比较运算符,在给定对象实例的情况下,该运算符检查该实例是否具有指定的类型(类/子类/接口)。 就像其他比较运算符一样,它返回true或false 。

    The following code shows how pattern matching for instanceof removes this redundant code(object casting ) by introducing a pattern variable. In Java14, the equals() method can be written as below.

    以下代码显示了instanceof的模式匹配如何通过引入模式变量来消除此冗余代码(对象转换)。 在Java14中, equals()方法可以编写如下。

    @Override public boolean equals(Object o) { return o instanceof Monitor other && model.equals(other.model) && price == other.price; }

    @Override public boolean equals(Object o) { return o instanceof Monitor other && model.equals(other.model) && price == other.price; }

    Pattern variables i.e “other” is the final local variables that are declared and initialized at the same place. With other final local variables, it is possible to declare them and defer their assignment. Also, you cannot assign another value to a pattern variable since it is implicitly final. The scope of the pattern variable is limited.

    模式变量(即“其他”)是在同一位置声明和初始化的最终局部变量。 使用其他最终局部变量 ,可以声明它们并推迟其赋值。 同样,您不能为模式变量分配另一个值,因为它隐式为final 。 模式变量的范围是有限的。

    2.切换表达式 (2. Switch Expressions)

    The current design of Java’s switch the statement follows closely languages such as C and C++, and supports fall through semantics by default. The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. Here’s an example of the classic switch statement with an enum:

    Java的switch的当前设计该语句紧密遵循C和C ++之类的语言 ,并且默认情况下支持通过语义。 Java switch语句从多个条件中执行一个语句。 就像if-else-if阶梯语句。 这是带有枚举的经典switch语句的示例:

    In the above code, the many break statements make it unnecessarily verbose, where missing break statements would mean accidental fall through.

    在上面的代码中,许多break语句使它变得不必要地冗长,丢失的break语句将意味着意外掉线。

    Switch expressions were first introduced in Java 12, got an improvement in Java 13, and will be a standard feature in Java 14.

    开关表达式最早是在Java 12中引入的,对Java 13进行了改进,并将成为Java 14的标准功能。

    Java 14 introduces a new form of switch label, “case L ->", to signify that only the code to the right of the label is to be executed if the label is matched. It also allows multiple constants per case, separated by commas.

    Java 14引入了一种新形式的开关标签“ case L->”,表示如果匹配标签,则仅执行标签右边的代码,并且每种情况允许多个常量,以逗号分隔。 。

    2. We extend the switch a statement so it can be used as an expression.

    2.我们将switch扩展为一条语句,以便可以将其用作表达式。

    3. Most switch expressions will have a single expression to the right of the "case L ->" switch label. In the event that a full block is needed, we introduce a new yield statement to yield a value, which becomes the value of the enclosing switch expression.

    3.大多数开关表达式在“ case L->”开关标签的右侧都有一个表达式。 如果需要一个完整的块,我们将引入一个新的yeld语句来产生一个值,该值成为封闭开关表达式的值。

    What’s the difference to a default return and yield?

    默认收益率和收益率有什么区别?

    A return statement returns control to the invoker of a method or constructor, while a yield statement transfers control by causing an enclosing switch expression to produce a specified value.

    return语句将控制权返回给方法或构造函数的调用者,而yield语句通过使封闭的switch表达式产生指定值来转移控制权。

    3.用Java14记录 (3. Record in Java14)

    Suppose We will have to create a data model say “Student” with attribute “name” and “id”. As developers, we are used to defining a data class, encapsulating variables to store its state. However, with a regular class, the rules are to define private instance variables to store the state of your data object, add public constructors, accessor or mutators methods, and override methods like toString(), equals(), and hashCode() from the Object class.

    假设我们将不得不创建一个数据模型,例如“ Student”,其属性为“ name”和“ id”。 作为开发人员,我们习惯于定义数据类,并封装变量以存储其状态。 但是,对于常规类,规则是定义私有实例变量以存储数据对象的状态,添加公共构造函数,访问器或mutators方法,并从中重写toString() , equals()和hashCode()之类的方法 。对象类。

    In Java 14, Records introduce a new type of declaration in Java, which simplifies the task of modeling your data as data. It also cuts down significantly on the boilerplate code. In Java 14 We can create a record as below.

    在Java 14中, Records在Java中引入了一种新型的声明,它简化了将数据建模为数据的任务。 它还大大减少了样板代码。 在Java 14中,我们可以创建以下记录。

    record StudentModel(String name, int id){}

    记录StudentModel(字符串名称,整数ID){}

    With just one line of code, the preceding example defines a record with components Name and id. By default, the compiler creates a bunch of methods for a record, like instance methods to store its state, constructors, getters (no setters-the intent to the data be immutable), and overrides toString(), equals(), and hashCode() method from the Object class.

    前面的示例仅用一行代码,定义了一条包含名称和ID的记录。 默认情况下,编译器为记录创建一堆方法,例如用于存储其状态,构造函数,getter( 无设置方法-数据的意图是不可变的 )的实例方法,并覆盖toString(),equals()和hashCode ()方法来自Object类。

    Java compiler defines a record as a final class, a record implicitly extends the java.lang.Record class from the core Java API. For each of the components (data variables), it defines, the compiler defines a final instance variable. Interestingly, the name of the getter methods is the same as the name of the data variable (and don’t start with ‘get’). Since a record is supposed to be immutable, no setter methods are defined.

    Java编译器将记录定义为最终类,该记录从核心Java API隐式扩展了java.lang.Record类。 对于它定义的每个组件(数据变量),编译器都定义一个最终实例变量。 有趣的是,getter方法的名称与数据变量的名称相同(并且不要以“ get”开头)。 由于假定记录是不可变的,因此未定义setter方法。

    The methods toString(), hashCode() and equals() are also generated automatically for records.

    方法toString(),hashCode()和equals()也会自动为记录生成。

    We can declare static variables, static method, and nonstatic method using the same syntax as a class:

    我们可以使用与类相同的语法来声明静态变量,静态方法和非静态方法:

    4. G1的NUMA感知内存分配 (4. NUMA-Aware Memory Allocation for G1)

    Non-uniform memory access (NUMA) is a way of configuring a cluster of microprocessors into a multiprocessing system, so that memory can be shared locally and performance can be improved and the system’s ability extended.

    非均匀内存访问(NUMA)是一种将微处理器集群配置为多处理系统的方式,因此可以在本地共享内存,可以提高性能并扩展系统的功能。

    To optimize memory access locality of Java server applications, There are two different Java heap configurations. The first one, NUMA-Eden, uses a NUMA-aware young generation and the original old generation of the HotSpot VM we used. The second one, NUMA-Eden+Old, uses both NUMA-aware young generation and NUMA-aware old generation. The NUMA-Eden configuration focuses on optimizing the locality of the accesses to the objects in the younggeneration whereas the NUMA-Eden+Old configuration focuses on optimizing the locality of the accesses to the objects in young and old generations. The NUMAEden+Old is more likely to be more effective than the NUMA-Eden since it targets all memory accesses in the application. However, it requires gathering object access frequencies by processors at runtime.

    为了优化Java服务器应用程序的内存访问位置,有两种不同的Java堆配置。 第一个是NUMA-Eden,它使用NUMA感知的年轻一代以及我们使用的HotSpot VM的原始老一代。 第二个是NUMA-Eden + Old,它使用NUMA感知的年轻一代和NUMA感知的老一代。 NUMA-Eden配置注重于优化对年轻一代对象的访问的位置,而NUMA-Eden + Old配置注重于对年轻一代和老年人的对象的访问的位置。 NUMAEden + Old比NUMA-Eden更有效,因为它针对应用程序中的所有内存访问。 但是,它要求处理器在运行时收集对象访问频率。

    G1’s heap is organized as a collection of fixed-size regions. A region is typically a set of physical pages, although when using large pages (via -XX:+UseLargePages) several regions may make up a single physical page.

    G1的堆组织为固定大小区域的集合。 一个区域通常是一组物理页面,尽管使用大页面(通过-XX:+ UseLargePages)时,多个区域可能组成一个物理页面。

    If the +XX:+UseNUMA option is specified then, when the JVM is initialized, the regions will be evenly spread across the total number of available NUMA nodes.

    如果指定了+XX:+UseNUMA选项,则在初始化JVM时,区域将平均分布在可用NUMA节点的总数上。

    In order to allocate a new object for a mutator thread, G1 may need to allocate a new region. It will do so by preferentially selecting a free region from the NUMA node to which the current thread is bound so that the object will be kept on the same NUMA node in the young generation. If there is no free region on the same NUMA node during region allocation for a mutator then G1 will trigger a garbage collection.

    为了为mutator线程分配新对象,G1可能需要分配一个新区域。 它将通过从NUMA节点中优先选择一个与当前线程绑定的空闲区域来执行此操作,以便将对象保留在年轻代中的同一NUMA节点上。 如果在为变量分配区域的过程中,同一NUMA节点上没有空闲区域,则G1将触发垃圾回收。

    5.卸下并发标记扫描(CMS)垃圾收集器 (5. Remove the Concurrent Mark Sweep (CMS) Garbage Collector)

    CMS GC was developed in response to an increasing number of applications that demand a GC with lower worst-case pause times than Serial or Parallel GC and where it is acceptable to sacrifice some application throughput to eliminate or greatly reduce the number of lengthy GC pauses.

    CMS GC的开发是为了响应越来越多的应用程序,这些应用程序要求具有比串行或并行GC更低的最坏情况暂停时间的GC,并且可以牺牲一些应用程序吞吐量来消除或大大减少冗长的GC暂停次数。

    In CMS GC, young garbage collections are similar to those of Parallel GC. They are parallel stop-the-world, meaning all Java application threads are paused during young garbage collections and the garbage collection work is performed by multiple threads. Note that you can configure CMS GC with a single-threaded young generation collector, but this option has been deprecated in Java 8 and is removed in Java 9.

    在CMS GC中,年轻垃圾收集与Parallel GC相似。 它们是并行的世界末日,这意味着所有Java应用程序线程在年轻的垃圾回收期间都将暂停,并且垃圾回收工作由多个线程执行。 请注意,您可以使用单线程年轻代收集器配置CMS GC,但是Java 8中已弃用该选项,而Java 9中已删除了该选项。

    CMS uses the parallel stop-the-world mark-copy algorithm in the Young Generation and concurrent mark-sweep algorithm in the Old Generation.Young Generation — Par New Collector — mark-copy Algorithm Old Generation — CMS Collector — mark-sweep Algorithm.

    CMS在Young Generation中使用并行世界停止标记复制算法,而在Old Generation中使用并发标记清除算法。YoungGeneration(同种新收集器)-标记复制算法Old Generation-CMS Collector(标记收集器)-标记清除算法。

    Performance Issues with CMS

    CMS的性能问题

    Concurrent Mode Failure: However, if the CMS collector is unable to finish reclaiming the unreachable objects before the tenured generation fills up, or if an allocation cannot be satisfied with the available free space blocks in the tenured generation, then the application is paused and the collection is completed with all the application threads stopped.

    并发模式失败:但是,如果CMS收集器无法在使用权产生的一代填满之前完成回收无法访问的对象,或者如果使用使用权产生的可用空闲空间块无法满足分配要求,则将暂停应用程序,并且收集已完成,所有应用程序线程均已停止。

    Excessive GC Time and OutOfMemoryError: The CMS collector throws an OutOfMemoryError if too much time is being spent in garbage collection: If more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, then an OutOfMemoryError is thrown.

    过多的GC时间和OutOfMemoryError:如果在垃圾回收上花费的时间过多,则CMS收集器将引发OutOfMemoryError:如果在垃圾回收中花费了总时间的98%以上,并且回收的堆少于2%,则抛出OutOfMemoryError 。

    Floating Garbage: It causes old Generation fragmentation and the lack of predictability in pause durations in some cases, especially on large heaps.

    浮动垃圾:在某些情况下,尤其是在大堆上,它会导致旧的碎片化以及暂停持续时间缺乏可预测性。

    Pauses: The CMS collector pauses an application twice during a concurrent collection cycle. The first pause is to mark as live the objects directly reachable from the roots (for example, object references from application thread stacks and registers, static objects, and so on) and from elsewhere in the heap (for example, the young generation)

    暂停: CMS收集器在并发收集周期中将应用程序暂停两次。 第一个暂停是将可从根直接访问的对象(例如,来自应用程序线程堆栈和寄存器的对象引用,静态对象等)和堆中其他位置(例如,年轻代)的标记为活动对象

    When trying to run the Java application with -XX:+UseConcMarkSweepGC, the error message now shown states: " Ignoring option UseConcMarkSweepGC; support was removed in 14.0".

    尝试使用-XX:+UseConcMarkSweepGC运行Java应用程序时,错误消息现在显示为:“忽略选项UseConcMarkSweepGC;在14.0中已删除支持”。

    6.有用的NullPointerExceptions (6. Helpful NullPointerExceptions)

    Java 14 improves the usability of NullPointerException generated by the JVM by describing precisely which variable was null.

    Java 14通过精确描述哪个变量为null来提高JVM生成的NullPointerException的可用性。

    When we execute the above program using any compiler older than java 14 , We will get the null pointer exception without any information which variable is null.

    当我们使用Java 14之前的任何编译器执行上述程序时,我们将获得null指针异常,而没有任何有关变量为null的信息。

    In Java14, We need to pass -XX:+ShowCodeDetailsInExceptionMessages JVM flag to enable this feature while running the application.We VM argument in intellij like this .

    在Java14中,我们需要传递-XX:+ ShowCodeDetailsInExceptionMessages JVM标志以在运行应用程序时启用此功能。intellij中的 VM参数是这样的。

    Now the output of the above program is as below, Now We can see which variable is null.

    现在上面程序的输出如下,现在我们可以看到哪个变量为空。

    7.弃用ParallelScavenge + SerialOld GC组合 (7. Deprecate the ParallelScavenge + SerialOld GC Combination)

    There is one combination of GC algorithms that we believe is very little used but requires a significant amount of maintenance effort: The pairing of the parallel young generation GC and the serial old GC . This combination must be specifically enabled by the user with the -XX:+UseParallelGC -XX:-UseParallelOldGC command line options. The only advantage of this combination compared to using a parallel GC algorithm for both the young and old generations is slightly lower total memory usage.

    我们认为GC算法的组合很少使用,但需要大量维护工作:并行年轻一代GC和串行旧GC的配对。 用户必须使用-XX:+ UseParallelGC -XX:-UseParallelOldGC命令行选项专门启用此组合。 与针对年轻人和老年人使用并行GC算法相比,此组合的唯一优势是总内存使用量略低。

    8. Java 14中的外部内存访问API (8. Foreign Memory Access API in Java 14)

    Java objects reside on the heap. However, this can occasionally lead to problems such as inefficient memory usage, low performance, and garbage collection issues. Native memory can be more efficient in these cases, but using it has been traditionally very difficult and error-prone.Java 14 introduces the foreign memory access API to access native memory more securely and efficiently. Before the introduction of the foreign memory access API in Java, there were two main ways to access native memory in Java. These are java.nio.ByteBuffer and sun.misc.Unsafe classes. There are some limitations with these api .

    Java对象驻留在堆上。 但是,这有时会导致诸如内存使用效率低下,性能低下以及垃圾回收等问题。 本机上存储器可以在这些情况下更有效,但使用它在传统上非常困难,error-prone.Java 14只介绍了国外内存访问API访问本机内存更安全和有效。 在Java中引入外部内存访问API之前,有两种主要的方法来访问Java中的本机内存。 这些是java.nio.ByteBuffer和sun.misc.Unsafe类。 这些api有一些限制。

    Incorrect use of a ByteBuffer can cause a memory leak and OutOfMemory errors. This is because an unused memory reference can prevent the garbage collector from deallocating the memory.

    错误使用ByteBuffer可能会导致内存泄漏和OutOfMemory错误。 这是因为未使用的内存引用可以防止垃圾回收器重新分配内存。

    Unsafe API allows the Java programs to crash the JVM due to illegal memory usage.

    不安全的API允许Java程序由于非法使用内存而使JVM崩溃。

    Foreign memory access API provides three important abstraction .

    外部存储器访问API提供了三个重要的抽象。

    MemorySegment : A MemorySegment is used to model a contiguous memory region with given spatial and temporal bounds.Let’s create a native memory segment of 200 bytes:MemorySegment memorySegment = MemorySegment.allocateNative(200);

    MemorySegment:使用MemorySegment对具有给定空间和时间范围的连续内存区域进行建模。让我们创建一个200字节的本机内存段:MemorySegment memorySegment = MemorySegment.allocateNative(200);

    MemoryAddress : MemoryAddress can be thought of as an offset within a segment.

    MemoryAddress: MemoryAddress可以视为段内的偏移量。

    MemoryLayout : MemoryLayout is a programmatic description of a memory segment’s contents.

    MemoryLayout: MemoryLayout是内存段内容的程序描述。

    9.文字块 (9. Text Blocks)

    Text Blocks were introduced as a preview feature in Java 13 with the goal to allow easy creation of multiline string literals. It’s useful in easily creating HTML and JSON or SQL query strings. In Java 14, Text Blocks are still in preview with some new additions. We can now use:tring text =””” I am Alok \ I am from Inida \ I am working in Oracle\ “””;

    文本块是Java 13中的预览功能,其目的是允许轻松创建多行字符串文字。 在轻松创建HTML和JSON或SQL查询字符串时很有用。 在Java 14中,文本块仍在预览中,并增加了一些新功能。 我们现在可以使用:tring text =“””我是Alok \我是Inida \我在Oracle \“”“工作;

    There are few more features like new packaging tools, Garbage Collection mechanism for window and mac Os, Some API deprecation and many more have been introduced in java14. We can get the list of all these features of JDK 14, You can get more and more information about these features. Please go through this link .

    很少有其他功能,例如新的打包工具,用于window和mac Os的垃圾收集机制,某些API弃用以及Java14中引入的更多功能。 我们可以获得JDK 14所有这些功能的列表,您可以获得有关这些功能的越来越多的信息。 请通过此链接。

    Happy Learning … :)

    快乐学习... :)

    翻译自: https://medium.com/javarevisited/what-is-new-in-java-14-39b164ee9c45

    java 1.8新增功能

    相关资源:java版本,1.8,1.6,1.14
    Processed: 0.014, SQL: 9