Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Wednesday, October 30, 2019

Java 13 API - What Are New Features? (JDK 13 Changes)

1. Introduction


In this article, We will learn what are the new features of Java 13 that are added to JDK 13.

Download JDK 13 from the Oracle official website.

Now we are going to learn about the following new changes step by step. Before that, you may have a question that "Is really JDK 13 has major changes?". Because a new java release is expected for every six months. So, Raising this question is common. Answer to this question is "no" changes are very minor. This does not impact the core developers. Except who closely works on CDS, ZGC, Socket API, and switch expressions (It is good to know).

Below is the complete list of changes in JDK 13.



JEP 350: Dynamic CDS Archives
JEP-351: ZGC: Uncommit Unused Memory
JEP-353: Reimplement the Legacy Socket API
JEP-354: Switch Expressions (Preview) (developer feature)
JEP-355: Text Blocks (Preview) (developer feature)

From this list, the first 3 changes can be used directly but the last two are in preview (developer feature). So, We can not use them directly. You will understand how to use the preview functionalities as we go through them each.



2. JEP 350 - Dynamic CDS Archives


JEP 310 Application Class-Data Sharing is introduced in JDK 10.


The main idea behind the feature "Class Data Sharing (CDS)" is to improve startup performance by creating class data as an archive. This can be reusable once the archive is created. So that the JVM need not recreate it again.

How to create a CDS Archive step by step?


Mainly, There are three essential steps required to create and use an archive with application class-data.

Creating a list of classes that should be included in the archive:

java -XX:+UseAppCDS
     -XX:DumpLoadedClassList=classes.lst
  -jar app.jar

Creating A Reusable Archive:

java -XX:+UseAppCDS -Xshare:dump 
     -XX:SharedClassListFile=classes.lst
     -XX:SharedArchiveFile=app-cds.jsa
     --class-path app.jar

Using the archive:

java -XX:+UseAppCDS -Xshare:on 
     -XX:SharedArchiveFile=app-cds.jsa
     -jar app.jar

"jsa" means "Java Sharing Archive".

We can create CDS in another way as below in two steps.

The CDS archives will be created if programs exist with "-XX:ArchiveClassesAtExit".

$ java -XX:ArchiveClassesAtExit=hello.jsa -cp hello.jar Hello

To execute the program from the CDS archives above step.


$  bin/java -XX:SharedArchiveFile=hello.jsa -cp hello.jar Hello

3. JEP 351 ZGC - Uncommit Unused Memory


ZGC is released as part of JDK 11. This is We've already seen about it "Shenandoah: Ultra low-pause garbage collector" for class unloading at runtime as part of JDK 12.
https://java-w3schools.blogspot.com/2019/04/java-12-shenandoah.html

The goal of ZGC is to provide a short pause time when cleaning up heap memories. Note that this GC pause times should not exceed 10ms.
However, It didn’t return the unused heap memory to the operating system, even though that memory is not used for a long time.

This JEP enhanced the ZGC by returning unused heap memory to the operating system.

4. JEP-353 Reimplement the Legacy Socket API


This is to introduce the new API for socket programmers. Since java 1.0, Socket API implementations are the same for the Socket interface and  ServerSocket.

These are very old code and difficult to debug and maintenance. Because the code is a mix of legacy c and java code. Now the JDK 13 API introduced new Socket default implementations.

Before JDK 13 code from API:


public class ServerSocket implements java.io.Closeable {
    /**
     * Various states of this socket.
     */
    private boolean created = false;
    private boolean bound = false;
    private boolean closed = false;
    private Object closeLock = new Object();

    /**
     * The implementation of this Socket.
     */
    private SocketImpl impl;

 // Some code
}


In Java 13 API:


ServerSocket is modified to use NioSocketImpl (or PlainSocketImpl) by default. It no longer uses the SOCKS implementation.

The new implementations, NioSocketImpl - is a drop-in replacement for PlainSocketImpl. It is developed to be easy to maintain and debug the applications. It shares the same JDK internal infrastructure as the New I/O (NIO) implementation so it doesn't need its own native code. Now it is super easy to improve the performance because it uses the java.util.concurrent lock.

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class JEP353UsingNewSocketAPI {

    public static void main(String[] args) {

        try (ServerSocket serverSocket = new ServerSocket(8888)){

            boolean running = true;
            while(running){

                Socket clientSocket = serverSocket.accept();
                //do something here with clientSocket
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Note: If anything goes wrong, We can still have an option to switch back to the old implementation PlainSocketImpl by setting jdk.net.usePlainSocketImpl system property.

5. JEP-354 Switch Expressions (Preview)


This is a preview feature in Java 13 and we can not use directly as part of JDK 13.

To use the preview features, we should use the flag "--enable-preview --release" at the time of compilation and "--enable-preview" at runtime.

See the commands below.

javac --enable-preview --release 13 ExampleCode.java
java --enable-preview ExampleCode

This enhancement is added to switch to return some value from it using the 'yield' keyword. To understand better, We'll see a few example programs before and after java 13.

Java 11 - Traditional Switch Statement:


Here storing the value in the String outputString variable inside switch cases.

public String getTextFromNumber(int number) {
    String outputString = "";
    switch (number) {
        case 1, 2:
            outputString = "one or two";
            break;
        case 3:
            outputString = "three";
            break;
        case 4, 5, 6:
            outputString = "four or five or six";
            break;
        default:
            outputString = "unknown";
            break;
    };
    return outputString;
}

Java 12 - Traditional Switch Statement:


In JDK 12, we can use the break statement to return the string values.

In the below example program, the switch is returning a string value through break keyword and storing it into a String variable.

public String getTextFromNumber(int number) {
    String outputString = switch (number) {
        case 1, 2:
            break "one or two";
        case 3:
            break "three";
        case 4, 5, 6:
            break "four or five or six";
        default:
            break "unknown";
    };
    return outputString;
}

Java 13 - Traditional Switch Statement:


The problem in Java 12, I see is that the code became non-readable and difficult to understand. So that the JDK team decided to introduce the new keyword yield such that it adds value to switch statements to become more readable.

Let us take a look at JDK 13 switch statement with yield.

public static String getTextFromNumber(int number) {
    return switch (number) {
        case 1, 2:
            yield "one or two ";
        case 3:
            yield " three ";
        case 4, 5, 6:
            yield " four or five or six ";
        default:
            yield " unknown ";
    };
}

Note: Switch statement code with break returns value no more accepted and not compiled in JDK 13. But it supports the lambda arrow "->" to return some value.


public static String getText(int number) {
    String returnValue = switch (number) {
        case 1, 2, 22 -> " one or two or twenty two";
        case 3, 30 -> " three or thirty";
        case 4, 5, 6, 40 -> "four or five or six or fourty";
        default -> "unknown number";
    };
 return returnValue;
}

6. JEP-355 Text Blocks (Preview)


In other programming languages such as Scala, JavaScript.

Text Blocks mean creating multiline strings. Before java 13, Java does not support the multi-line strings. Finally, Java started supporting text blocks. This is good for many developers who do string concatenation for each line. Adding the HTML or JSON content to string is very difficult and code looks ugly.

Before JDK 13:


String html ="<html>\n" +
    "   <body>\n" +
    "      <p>Hello, Welocme to Java-W3schools blog</p>\n" +
    "   </body>\n" +
    "</html>\n";

    
String json ="{\n" +
    "   \"name\":\"Venkatesh\",\n" +
    "   \"age\":30,\n" +
    "   \"location\":\"India\"\n" +
    "}\n";


In Java 13:


We should wrap the string inside Tripple Quotes as in """.

String html ="""
     <html>
       <body>
             <p>Hello, Welocme to Java-W3schools blog</p>\n" +
          </body>
        </html>
   """;

    
String json ="""
    "name": "Venkatesh",
    "age":30,
    "location":"India"
       """;


7. Conclusion


In this tutorial, We've seen the new changes added to JDK 13. Apparently, these are minor changes but should know the changes added. This would make you be front in the tech stand.

Putting the points that we learned today.

What is the CDS archive? How to create and reuse them?
ZGC sends the unused heap memory to the operating system.
New changes to Socket API and how to revert to old API using system property.
A new keyword "yield" is introduced to return a value from switch expression cases which make code easy to understand.
Use triple quotes """ to create String(Text) blocks such as HTML content and JSON instead of using string concat.

8. References


This tutorial is crafted based on the official docs.

OpenJdk 13

Oracle Offical update on JDK 13

Java 13: CDS Archive Examples

Java 13: Text blocks examples

JDK 13 Text Blocks creation notes

Java Version release from Wikipedia

Java 13: Switch Offical preview notes

New Socket API official docs

No comments:

Post a Comment

Please do not add any spam links in the comments section.