$show=/label

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

SHARE:

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...

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

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,2,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,20,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,71,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,2,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,47,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Softwares,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,2,Streams,11,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,7,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 13 API - What Are New Features? (JDK 13 Changes)
Java 13 API - What Are New Features? (JDK 13 Changes)
https://1.bp.blogspot.com/-a86ujf5dc0U/Xbm2xHYVhCI/AAAAAAAAB2M/FdEv04BbizMRt-6r7BJYaCfBy_04_yVQgCLcBGAsYHQ/s400/Java%2B13%2BAPI%2B-%2BWhat%2BAre%2BNew%2BFeatures%253F%2B%2528JDK%2B13%2BChanges%2529.png
https://1.bp.blogspot.com/-a86ujf5dc0U/Xbm2xHYVhCI/AAAAAAAAB2M/FdEv04BbizMRt-6r7BJYaCfBy_04_yVQgCLcBGAsYHQ/s72-c/Java%2B13%2BAPI%2B-%2BWhat%2BAre%2BNew%2BFeatures%253F%2B%2528JDK%2B13%2BChanges%2529.png
JavaProgramTo.com
https://www.javaprogramto.com/2019/10/java-13-new-features.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/10/java-13-new-features.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content