Core Java

The New Features in Java 13

In this article, we will see what are the new features available in Java version JDK 13.

1. Java 13 – Introduction

java 13

JDK 13 is the open-source reference implementation of version JDK 13 version of the Java SE Platform as specified by JSR 388 in the Java Community Process. Below are some of the main changes done in Java 13. This is not an exhaustive list. There are other minor changes as well which you can get from the JEPs.

2. Switch Expressions

JDK12 included the switch expression feature. The summary of the change is to extend the switch statement so that it can either be used as a statement or an expression, and that both forms can use either a traditional or simplified scoping and control flow behavior. Java 13 build on the previous version by adding yield. In Java 12 we can use switch statement as below:

private static String testSwitch(String value) {
    return switch (value) {
        case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> "Weekday";
        case "SATURDAY", "SUNDAY" -> "Weekend";
        default -> "Invalid";
    };
}

With Java 13 we can change the above expression to the more traditional switch statement by using yield:

private static String testSwitch(String value) {
    return switch (value) {
        case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY": yield "Weekday";
        case "SATURDAY", "SUNDAY": yield "Weekend";
        default: yield "Invalid";
    };
}

A switch expression can, like a switch statement, also use a traditional switch block with “case L:” switch labels (implying fall through semantics).

3. Text Blocks

A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over the format when desired. The goal of this feature is to simplify the task of writing Java programs by making it easy to express strings that span several lines of source code while avoiding escape sequences in common cases.

Before Java 13 if we have a string which is represented in multiple line we need to use escape character to represent it like below:

String sql = "SELECT * \n" +
        "          FROM Table\n" +
        "          WHERE id = 1\n";

With Java 13 we can write the above code as:

String html = """
          SELECT *
          FROM Table
          WHERE id = 1
          """;

A text block is a new kind of literal in the Java language. It may be used to denote a string anywhere that a string literal could appear, but offers greater expressiveness and less accidental complexity. A text block consists of zero or more content characters, enclosed by opening and closing delimiters. The opening delimiter is a sequence of three double-quote characters (""") followed by zero or more white spaces followed by a line terminator. The content begins at the first character after the line terminator of the opening delimiter.

4. Dynamic CDS Archives

Archiving application classes using AppCDS in HotSpot provides additional startup time and memory benefits relative to the default CDS archive. However, currently, a three-step procedure is required in order to use AppCDS for a Java application:

  • Do one or more trial runs to create a class list
  • Dump an archive using the created class list
  • Run with the archive

This procedure, moreover, works only for applications that use only built-in class loaders. Dynamic archiving enabled by a command-line option will simplify AppCDS usage by eliminating trial runs (step 1 above) and will support both built-in class loaders and user-defined class loaders effectively and uniformly.

A follow-up enhancement to this JEP could perform automatic archive generation during the first run of an application. This would eliminate the explicit archive creation step (step 2 above). The usage of CDS/AppCDS could then be completely transparent and automatic.

A shared archive is dynamically created when an application exits if the –XX:ArchiveClassesAtExit option is specified.

The dynamically-generated archive is created on top of the default system archive packaged with the running JDK image. A separate top-layer archive file is generated for each application. The user can specify the filename of the dynamic archive name as the argument to the -XX:ArchiveClassesAtExit option. For example, the following command creates jcg.jsa:

% bin/java -XX:ArchiveClassesAtExit=jcg.jsa -cp jcg.jar Java Code Geeks
To run the same application using this dynamic archive:

% bin/java -XX:SharedArchiveFile=jcg.jsa -cp jcg.jar Java Code Geeks

5. ZGC – Uncommit unused memory

ZGC does not currently uncommit and return memory to the operating system, even when that memory has been unused for a long time. This behavior is not optimal for all types of applications and environments, especially those where memory footprint is a concern.

The uncommit capability will be enabled by default. But whatever the policy decides, ZGC should never uncommit memory so that the heap goes below its minimum size (-Xms). This means the uncommit capability is effectively disabled if the JVM is started with a minimum heap size (-Xms) that is equal to the maximum heap size (-Xmx). The option -XX:-ZUncommit is also provided to explicitly disable this feature.

An uncommit delay can be configured using -XX:ZUncommitDelay= (defaults to 300 seconds). This delay specifies for how long memory should have been unused before it’s eligible for uncommit.

6. Reimplement the legacy Socket API

The java.net.Socket and java.net.ServerSocket APIs, and their underlying implementations, date back to JDK 1.0. The implementation is a mix of legacy Java and C code that is painful to maintain and debug. The implementation uses the thread stack as the I/O buffer, an approach that has required increasing the default thread stack size on several occasions. The implementation uses a native data structure to support asynchronous close, a source of subtle reliability and porting issues over the years. The implementation also has several concurrency issues that require an overhaul to address properly. In the context of a future world of fibers that park instead of blocking threads in native methods, the current implementation is not fit for purpose.

In Java 13 version this will be replaced by a simpler and more modern implementation that is easy to maintain and debug. The new implementation will be easy to adapt to work with user-mode threads, a.k.a. fibers.

7. New Methods for Creating DOM and SAX Factories

New methods have been added for instantiating DOM and SAX factories with Namespace support by default. These methods are prefixed over their existing counterparts with “NS,” which stands for NamespaceAware. Below is a list of the new methods:

  • newDefaultNSInstance()
  • newNSInstance()
  • newNSInstance(String factoryClassName, ClassLoader classLoader)

Using these new methods, a parser created through the factory will be NamespaceAware by default. For example, the following statement:

DocumentBuilder db = DocumentBuilderFactory.newDefaultNSInstance().newDocumentBuilder();

is equivalent to:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newDefaultInstance(); 
dbf.setNamespaceAware(true); 
DocumentBuilder db = dbf.newDocumentBuilder();

8. Miscellaneous

  • Three new methods have been added to java.nio.file.FileSystems to make it easier to use file system providers that treat the contents of a file as a file system.
    • newFileSystem(Path)
    • newFileSystem(Path, Map)
    • newFileSystem(Path, Map, ClassLoader)
  • java.nio.ByteBuffer and the other buffer types in java.nio now define absolute bulk get and put methods to transfer contiguous sequences of bytes without regard to or effect on the buffer position.
  • The manageable command-line flag -XX:SoftMaxHeapSize= has been added. Currently, it only has an effect when the Z garbage collector is enabled (-XX:+UseZGC). When set, the GC will strive to not grow the heap beyond the specified size, unless the GC decides it’s necessary to do so to avoid OutOfMemoryError. The softmax heap size is not allowed to be set to a value greater than the maximum heap size (-Xmx). When not set on the command line, it defaults to a value equal to the maximum heap size.
  • The SunPKCS11 provider has been updated with support for PKCS#11 v2.40. This version adds support for more algorithms such as the AES/GCM/NoPadding cipher, DSA signatures using the SHA-2 family of message digests, and SASSA-PSS signatures when the corresponding PKCS11 mechanisms are supported by the underlying PKCS11 library.
  • The Kerberos client has been enhanced with the support of principal name canonicalization and cross-realm referrals, as defined by the RFC 6806 protocol extension.

9. Summary

In this article, we learned about some of the changes in Java JDK 13 version. We learned about some of the most important changes and also looked at some API changes as well. This is not the complete list. There are other changes as well which you can look at JDK13 changes.

You can now check how to Download and Install Java Development Kit (JDK) 13.

Mohammad Meraj Zia

Senior Java Developer
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button