JavaRush /Java Blog /Random EN /Java 14: what's new?

Java 14: what's new?

Published in the Random EN group
The world's problems are the world's problems, and the new Java is on schedule. That is, exactly once every six months. The release version of Java 14 was released on March 17, and introduced several interesting innovations to the language aimed at developers. Among them are experimental support for the recordJava 14: what's new?  - 1 keyword , support for pattern matching in the " instanceof " operator, more user-friendly NullPointerExceptions , expanded “previewing” of text blocks , an updated default switch , and much more. Let us remind you that all innovations in Java begin with extension proposals ( JEP, Java Enhancement Proposals ). Developers propose changes, they are reviewed by the “official” Java parents, and then some of those changes are accepted, after which they become part of the JDK. And now - about everything in order.

JEP 359: Records

Records, also known as Records, are available for JDK 14 in preview mode, and this is something completely new for Java. In fact, we have before us a new type that was developed during the Valhalla project . Records are similar to enumerations and allow you to simplify your code. Essentially, they replace classes that have state but no behavior. Simply put, there are fields, no methods. In the case of classes, we sometimes have to write a lot of repetitive code that is not always necessary: ​​constructors, accessors, equals(), hashCode(), toString(), etc. To avoid this repetitive code, Java plans to use record. Here's the classic version:
final class Triangle {
 	public final int x;
public final int y;
public final int z;

    public Triangle(int x, int y, int z) {
         this.x = x;
         this.y = y;
    this.z = z;
    }
    // equals, hashCode, toString
Let's move to Java 14 and use record:
public record Triangle(int x, int y, int z){}
That's all. Please note that the recordings currently exist in preview form, so to try them out in practice you need to download jdk14 and enter the command:
javac —enable-preview —release 14 Triangle.java
Records are classes, albeit with limitations. They cannot extend other classes or declare fields (except private final which correspond to state declaration components). Records are implicitly final and cannot be abstract. Records differ from regular classes in that they cannot separate their API from its representation. But the loss of freedom is compensated by increased accuracy. Record components are also implicitly final.

JEP 305: Pattern Matching for instanceof (Preview)

The Pattern Matching feature , introduced in Java 14 in preview, is designed to combine checking the type of an object and its conversion in the instanceof operator. In other words, before Java 14 there would have been, for example, the following code:
Object object = Violin;

if (object instanceof Instrument) {
    Instrument instrument = (Instrument) object;
    System.out.println(instrument.getMaster());
}
As you can see, we must cast the object to the class whose methods we want to use. Now Java 14 and the connected Pattern Matching feature allows you to reduce the code to the following:
Object object = Violin;

if (object instanceof Instrument instrument){
    System.out.println(instrument.getMaster());
}

JEP 343: Packaging Tool (Incubator)

JDK 8 had a javapackager tool designed for JavaFX. However, following the separation of JavaFX from Java with the release of JDK 11, the popular javapackager was no longer available. Javapackager was a packaging tool. It allowed Java applications to be packaged in such a way that they could be installed like all other “normal” programs. For example, create exe files for Windows users and launch a Java application like a human - with a double click. Of course, such a tool is sorely lacking, so JEP 343 introduced a new tool, jpackage , which packages a Java application into a platform-specific package containing all the necessary dependencies. Supported package formats for a specific platform:
  • Linux: deb and rpm
  • macOS: pkg and dmg
  • Windows: MSI and EXE

JEP 345: NUMA-Aware Memory Allocation for G1

JEP 345 serves solely to implement NUMA (Non-uniform memory access) support. These are heterogeneous memory access architectures, a way of setting up a microprocessor cluster into a multiprocessor system in which memory can be distributed locally: each processor core gets a small amount of local memory, while other cores have access to it. JEP 345 plans to equip the G1 garbage collector with the ability to leverage such architectures. Among other things, this approach helps improve performance on very powerful machines.

JEP 349: JFR Event Streaming

Java Flight Recorder (JFR) is now part of OpenJDK and is therefore freely available. JDK 14 adds an API for on-the-fly tracking of JFR events (JDK Flight Recorder), in particular for organizing continuous monitoring of active and inactive applications. The same events are recorded as for the non-streaming option, with an overhead of less than 1%. This way the events will be streamed at the same time as the non-streaming option. However, JEP 349 must not allow synchronous callbacks for the corresponding consumer. Even data from records stored in intermediate memory should not be accessible. Technically, the jdk.jfr.consumer package in the jdk.jfr module will be extended with functionality for asynchronous access to events.

JEP 352: Non-Volatile Mapped Byte Buffers

As you know, the Java NIO (New IO) File API has been around since JDK 1.4, and then a new enhancement called Path was introduced. Path is an interface that replaces the java.io.File class as a representation of a file or directory when we work in Java NIO. JEP 352 extends MappedByteBuffer to load a portion of file data into non-volatile memory (NVM). This computer memory, in which data will not be lost even if the power is turned off (often called read-only memory), is used to permanently store data. This Java enhancement proposal provides a new module and class for the JDK API: the jdk.nio.mapmode module, which offers new modes (READ_ONLY_SYNC, WRITE_ONLY_SYNC) for creating mapped byte buffers (MappedByteBuffer) referencing NVM.

JEP 358: Helpful NullPointerExceptions

NullPointerExceptions will now be more programmer friendly. In the sense that the description of the exception will be much more informative than before. This is because the JVM has been taught to more accurately analyze program bytecode instructions, and it can indicate which variable leads to a zero value. Let's say we have the code:
a.getMessage().getUserInfo().getName()
In any of the latest Java we will get the usual error log, which does not answer the question of who exactly is null:
Exception in thread "main" java.lang.NullPointerException
	at Main.main(Main.java:12)
And here’s what Java 14 will give you if you decide to try this preview feature:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "UserInfo().getName()" because the return value of "Message().getUserInfo()" is null
	at Main.main(Main.java:12)
This chain is much more understandable and allows you to tackle the error much faster.

JEP 361: Switch Expressions (Standard)

The updated Switch operator was available in previous Java 12 and 13, but only as a preview feature, that is, it was not enabled by default. Now in JDK 14 everything works out of the box. Java 14 introduces a new simplified form of the switch block with case L -> ... labels. The new form simplifies the code in some cases. Here are a couple of examples. Let's say we have an enum that describes the days of the week. We can write classic code (pre-Java 14):
switch (day) {
    case MONDAY:
    case FRIDAY:
    case SUNDAY:
        System.out.println(6);
        break;
    case TUESDAY:
        System.out.println(7);
        break;
    case THURSDAY:
    case SATURDAY:
        System.out.println(8);
        break;
    case WEDNESDAY:
        System.out.println(9);
        break;
}
And here is an option using Java 14:
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);
}
You can also write multi-line blocks and return a value with the new yield keyword:
int result = switch (s) {
    case "Working from Home" -> 1;
    case "Working from Office" -> 2;
    default    -> {
        System.out.println("Neither Home nor Office… Cafe? Car? Park?...");
        yield 0;
    }
};
There are a few more important things to keep in mind when using the new switch s . In particular, you need to remember that the options must be exhaustive. That is, for all possible values ​​there must be a corresponding switch label. Since yield is now a keyword, a class called yield is possible in Java 14. In general, if you want to learn how to use the updated switches, go to JEP 361 and study. There's a lot of interesting information there.

JEP 362: Deprecate the Solaris and SPARC Ports

It is unlikely that many of our readers remember about the Solaris operating system . This UNIX-based operating system, created by Java's parents, Sun Microsystems, was used primarily for servers on the SPARC architecture... Too many unfamiliar words per square centimeter? No big deal: JEP 362 ends support for the Solaris/SPARC, Solaris/x64, and Linux/SPARC platforms. That is, their ports are now Deprecated, and in the future they will most likely be removed from OpenJDK. However, older versions of Java (prior to JDK 14) regarding the Solaris/SPARC, Solaris/x64 and Linux/SPARC ports should work without modification. If you are a history buff and are interested in technologies of the not-so-distant past, go to Wikipedia and read about the SPARС architecture .

JEP 363: Remove the Concurrent Mark Sweep (CMS) Garbage Collector

The CMS garbage collector (Concurrent Mark Sweep) is targeted for removal because two years ago it was marked as obsolete and left unmaintained. However, users of older versions of Java using the CMS GC can exhale - the purpose of this JEP is not to remove the builder from earlier JDK releases. In addition, the combination of ParallelScavenge and SerialOld garbage collection algorithms (running with the "-XX:+UseParallelGC -XX:-UseParallelOldGC" options) has been deprecated.

JEP 364: ZGC on macOS and JEP 365: ZGC on Windows

There is an interesting garbage collector called Z Garbage Collector (ZGC) . It works in passive mode, and tries to minimize delays due to garbage collection: the stopping time when using ZGC does not exceed 10 ms. It can work with small heaps and giant ones (those that take up many terabytes). JEP 364 and JEP 365 are practically twins. JEP 364 brings Z Garbage Collector to MacOS. Part of the JEP also describes the collector functionality for freeing unused device memory, as specified in JEP 351 , this has been happening since Java 13. The ZGC implementation on macOS has two parts:
  • Multi-mapping memory support on macOS
  • ZGC support for continuous memory reservation
JEP 365 provides support for ZGC already on Windows, and also in experimental mode. It is as follows:
  • Multi-mapping memory support
  • Support for memory mapping based on the page file into a reserved address space
  • Support for mapping and unmapping arbitrary parts of the heap
  • Support for committing and uncommitting arbitrary parts of the heap

JEP 366: Deprecate the ParallelScavenge + SerialOld GC Combination

This JEP deprecates the combination of Parallel Scavenge and Serial Old garbage collection algorithms. This combination had to be enabled manually using the command line parameters -XX: + UseParallelGC -XX: -UseParallelOldGC. The authors believe that the combination is very specific, but also requires significant maintenance effort. So now the -XX: UseParallelOldGC option is deprecated and a warning will appear if used.

JEP 367: Remove the Pack200 Tools and API

Pack200 is an archive format optimized for storing compiled Java class files. This tool has been marked deprecated since Java 11. Now the pack200, unpack200 and Pack200 API tools have been officially announced for removal from the java.util.jar package . This technology was introduced back in Java 5 as a means of dealing with very limited bandwidth (modems, it’s scary to say and remember, 56k) and insufficient storage space on hard drives. Some time ago, Java 9 introduced new compression schemes. Developers are encouraged to use jlink .

JEP 368: Text Blocks (Second Preview)

Text blocks first appeared in Java 13. They are multiline string literals that prevent the need for most escape sequences, automatically format the string, and also allow the developer to format the string if necessary. This useful feature is now available in Java 14 (2nd Preview). The main purpose of text blocks is to improve handling of confusing multi-line literals. This greatly simplifies reading and writing SQL queries, HTML and XML code, and JSON. Example HTML without text blocks:
String html = "<html>\n" +
              "    <body>\n" +
              "        <p>Hello, JavaRush Student</p>\n" +
              "    </body>\n" +
              "</html>\n";
How to represent the same with text blocks:
String html = """
              <html>
                  <body>
                      <p>Hello, JavaRush Student</p>
                  </body>
              </html>
              """;
The opening delimiter is a sequence of three double quote characters ("" "), followed by zero or more spaces, and then a line delimiter. The content begins at the first character after the line delimiter of the opening delimiter. The closing delimiter is a sequence of three double quote characters " " _ ) were chosen so that the characters could be displayed without escaping, and also visually distinguish a text block from a string literal. In early 2019, JEP 355 proposed text blocks as a continuation of JEP 326 (Raw String literals), but they were withdrawn. Later that year, JDK 13 introduced the text block preview feature, and now Java 14 has added two new escape sequences. This is a line-terminator, denoted \, and the second is for single space, denoted /s. An example of using newlines without text blocks:
String literal = "This is major Tom to Ground Control " +
"I am stepping through the door... " +
"Wait… What???";
And now with the escape sequence \<line-terminator>:
String text = """
                This is major Tom to Ground Control \
                I am stepping through the door... \
                WaitWhat???\
                """;
The escape sequence \s is used to account for trailing whitespace, which is ignored by the compiler by default. It preserves all whitespace that precedes it. Example:
String text1 = """
               line1
               line2 \s
               line3
               """;

String text2 = "line1\nline2 \nline3\n";
text1and text2are identical.

JEP 370: Foreign-Memory Access API (Incubator)

Many popular Java libraries and programs have access to external memory. For example, Ignite, MapDB, Memcached and Netty ByteBuf API. In doing so, they can avoid the cost and unpredictability associated with garbage collection (especially when serving large caches), share memory across multiple processes, and serialize and deserialize memory contents by mapping files in memory (for example, using mmap). However, the Java API still does not have a suitable solution for accessing external memory. JDK 14 includes a preview of the Foreign-Memory Access API , which allows Java applications to securely and efficiently access memory regions outside the JVM heap using the new MemorySegment, MemoryAddress, and MemoryLayout abstractions.

conclusions

So what do you think? Compared to Java 13, the new Java 14 offers many more important improvements in a variety of areas. Most likely, the most important for developers will be the updated switch, extended exceptions NullPointerExceptions and records. Or not?.. Don't forget to try out the new features of Java 14, it is very useful even for beginners. Good luck with your studies!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION