JDK13 - Java 13 - What's new features in Java 13
JDK 13 is the open-source reference implementation of version 13 of the Java SE Platform. JDK 13 reached General Availability on 17 September 2019
- Dynamic CDS Archives
- ZGC: Uncommit Unused Memory
- Reimplement the Legacy Socket API
- Switch Expressions (Preview)
- Text Blocks (Preview)
-
Dynamic CDS Archives: Commercial class-data sharing (CDS) feature was there since Java 8, however it gets evolved over several Java releases (10,12,13). Java 13 extended the feature to allow the dynamic archiving
of classes at the end of Java application execution.
The concept behind AppCDS is to create and share a class data archive once, so that the JVM does not need to recreate it. AppCDS greatly reduces the amount of time JVM spends on loading classes.Important Notes: Application class-data sharing can be achieved in below ways in different version of jdk.
- Java 10: Can be achieved by using below 3 commands
# create a list of classes in the archive $ java -XX:DumpLoadedClassList=classes.lst -jar helloApp.jar # create the archive $ java -Xshare:dump -XX:SharedClassListFile=classes.lst -XX:SharedArchiveFile=hello-app-cds.jsa --class-path helloApp.jar # use the archive $ java -XX:SharedArchiveFile=hello-app-cds.jsa -jar helloApp.jar
- Java 12: Java classes are loaded automatically from the JDK archive.
- Java 13: The JVM will automatically create class-data archives when shutdown with the below
XX:ArchiveClassesAtExit
option.
# creates helloApp.jsa
$ bin/java -XX:ArchiveClassesAtExit=helloApp.jsa -cp helloApp.jar Hello
# run the helloApp application using this dynamic archive
$ bin/java -XX:SharedArchiveFile=helloApp.jsa -cp helloApp.jar Hello
Take a look at our Suggested Posts :
ZGC: Uncommit Unused Memory
: Java 11 has introduced Z Garbage Collector (ZGC), which had short pause while cleaning up the heap memories and it was not returning unused memory to operating system even though memory was unused for long time. Now Java 13 has extended the feature to return unused heap memory to the operating system.Reimplement the Legacy Socket API
: Java 13 replaces the underlying implementation used by thejava.net.Socket
and java.net.ServerSocket
APIs with a simpler and more modern
implementation that is easy to maintain and debug.
Before Java 13 using the PlainSocketImpl for the SocketImpl, date back to JDK 1.0, it is a mix of legacy Java and C code that is hard to maintain and debug.// ServerSocket.java
public class ServerSocket implements java.io.Closeable {
/**
* Socket Implementation
*/
private SocketImpl socketImpl;
}
Java 13: it introduces a new NioSocketImpl class as a replacement for PlainSocketImpl.
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class JEP353 {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(8888)){
boolean running = true;
while(running){
Socket clientSocket = serverSocket.accept();
........
}
} catch (IOException execption) {
execption.printStackTrace();
}
}
}
Switch Expressions (Preview)
This is a preview feature, JEP 13 is planning to extend switch statement, which can be used as an expression with help of arrow (->), and now can yield/return the value.EXAMPLE-1
Before Java 13
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;
}
Java 13 enhancements
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);
}
EXAMPLE-2
Before Java 13
int numLetters;
switch (day) {
case MONDAY:
case FRIDAY:
case SUNDAY:
numLetters = 6;
break;
case TUESDAY:
numLetters = 7;
break;
case THURSDAY:
case SATURDAY:
numLetters = 8;
break;
case WEDNESDAY:
numLetters = 9;
break;
default:
throw new IllegalStateException("Wat: " + day);
}
Java 13 enhancements
int numLetters = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
};
More Examples
//Arrow labels
static void grade(int g) {
System.out.println(
switch (g) {
case 1 -> "A";
case 2 -> "B";
default -> "C";
}
);
}
------------------------------------------
//Yielding a value - introduce a new yield
int j = switch (day) {
case MONDAY -> 0;
case TUESDAY -> 1;
default -> {
int d = day.toString().length();
int result = f(d);
yield result;
}
};
JEP 355: Text Blocks (Preview)
In Java, to embed HTML, XML, SQL, or JSON snippet into a code is often hard to read and hard to keep, and to overcome this problem, Java 14 has introduced Text Block.
A text block contains zero or more content characters, which are enclosed by open and close delimiters.
HTML Example Without Text BlockString html = "<html>\n" +
" <body>\n" +
" <p>Hello, world</p>\n" +
" </body>\n" +
"</html>\n";
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.
The closing delimiter is a sequence of three double quote characters. The content ends at the last character before the first double quote of the closing delimiter.
The content may include double quote characters directly, unlike the characters in a string literal. The use of \" in a text block is permitted, but not necessary or recommended. Fat delimiters (""") were chosen so that " characters could appear unescaped, and also to visually distinguish a text block from a string literal.
A text block is a multi-line string literals which prevents the need for most escape sequences, formats the string automatically, and allows the developer and gives control to format the string if necessary.
HTML Example With Text BlockString html = """
<html>
<body>
<p>Hello, world</p>
</body>
</html>
""";
In early 2019, JEP 355 proposed text blocks as a follow-up to the JEP 326 (Raw String literals) exploration, which had been withdrawn.
More ExamplesSQL example Without Text Block
String query = "SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB`\n" +
"WHERE `CITY` = 'INDIANAPOLIS'\n" +
"ORDER BY `EMP_ID`, `LAST_NAME`;\n";
SQL example With Text Block
String query = """
SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB`
WHERE `CITY` = 'US'
ORDER BY `EMP_ID`, `LAST_NAME`;
Polyglot language example Without Text Block
ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
Object obj = engine.eval("function hello() {\n" +
" print('\"Hello, world\"');\n" +
"}\n" +
"\n" +
"hello();\n");
Polyglot language example With Text Block
ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
Object obj = engine.eval("""
function hello() {
print('"Hello, world"');
}
hello();
""");
The content may include line terminators directly, unlike the characters in a string literal. The use of \n in a text block is permitted, but not necessary or recommended. For example, the text block:
//using text block
"""
line 1
line 2
line 3
"""
//is equivalent to the string literal
"line 1\nline 2\nline 3\n"
//or a concatenation of string literals
"line 1\n" +
"line 2\n" +
"line 3\n"
Second Example
//using text block
"""
line 1
line 2
line 3"""
//is equivalent to the string literal
"line 1\nline 2\nline 3"
Quick glance on earlier Java Versions Features :
Java 12 Features
- Shenandoah: A Low-Pause-Time Garbage Collector (Experimental)
- Microbenchmark Suite
- Switch Expressions (Preview)
- JVM Constants API
- One AArch64 Port, Not Two
- Default CDS Archives
- Abortable Mixed Collections
- Promptly Return Unused Committed Memory from G1
Java 11 Features
- 181: Nest-Based Access Control
- 309: Dynamic Class-File Constants
- 315: Improve Aarch64 Intrinsics
- 318: Epsilon: A No-Op Garbage Collector
- 320: Remove the Java EE and CORBA Modules
- 321: HTTP Client (Standard)
- 323: Local-Variable Syntax for Lambda Parameters
- 324: Key Agreement with Curve25519 and Curve448
- 327: Unicode 10
- 328: Flight Recorder
- 329: ChaCha20 and Poly1305 Cryptographic Algorithms
- 330: Launch Single-File Source-Code Programs
- 331: Low-Overhead Heap Profiling
- 332: Transport Layer Security (TLS) 1.3
- 333: ZGC: A Scalable Low-Latency Garbage Collector(Experimental)
- 335: Deprecate the Nashorn JavaScript Engine
- 336: Deprecate the Pack200 Tools and API
Java 10 Features
- Local-variable type inference
- Experimental Java-based JIT compiler.This is the integration of the Graal dynamic compiler for the Linux x64 platform
- Application class-data sharing. This allows application classes to be placed in the shared archive to reduce startup and footprint for Java applications
- Time-based release versioning
- Parallel full GC
- Garbage-collector interface
- Additional Unicode language-tag extensions
- Root certificates
- Thread-local handshakes
- Heap allocation on alternative memory devices
- Remove the native-header generation tool - javah
- Consolidate the JDK forest into a single repository
Java 9 Features
- Modularization of the JDK under Project Jigsaw (Java Platform Module System)
- jshell: The Java Shell (a Java REPL)
- Ahead-of-time compilation
- XML catalogs
- More concurrency updates. It includes a Java implementation of Reactive Streams, including a new Flow class that included the interfaces previously provided by Reactive Streams
- Variable handles: define a standard means to invoke the equivalents of various java.util.concurrent.atomic and sun.misc.Unsafe operations
- jlink: The Java Linker: create a tool that can assemble and optimize a set of modules and their dependencies into a custom run-time image. It effectively allows to produce a fully usable executable including the JVM to run it
- JavaDB was removed from JDK
- HiDPI graphics: automatic scaling and sizing
Java 8 Features
- Language-level support for lambda expressions and default methods (virtual extension methods) which allow the addition of methods to interfaces without breaking existing implementations.
- Project Nashorn, a JavaScript runtime which allows developers to embed JavaScript code within applications
- Annotation on Java types
- Unsigned integer arithmetic
- Repeating annotations
- Date and time API
- Statically-linked JNI libraries
- Launch JavaFX applications (direct launching of JavaFX application JARs)
- Remove the permanent generation
Java 7 Features
- JVM support for dynamic languages
- Compressed 64-bit pointers
- Strings in switch
- Automatic resource management in try-statement
- Improved type inference for generic instance creation, aka the diamond operator <>
- Simplified varargs method declaration
- Binary integer literals
- Allowing underscores in numeric literals
- Catching multiple exception types and rethrowing exceptions with improved type checking
- Concurrency utilities
- New file I/O library adding support for multiple file systems
- Timsort is used to sort collections and arrays of objects instead of merge sort
- Library-level support for elliptic curve cryptography algorithms
- An XRender pipeline for Java 2D, which improves handling of features specific to modern GPUs
- New platform APIs for the graphics features
- Enhanced library-level support for new network protocols, including SCTP and Sockets Direct Protocol
- Upstream updates to XML and Unicode
- Java deployment rule sets
Java 6 Features
- Support for older Win9x versions dropped
- Scripting Language Support
- Dramatic performance improvements for the core platform, and Swing.
- Improved Web Service support through JAX-WS.
- JDBC 4.0 support.
- Java Compiler API
- Upgrade of JAXB to version 2.0
- Support for pluggable annotations
- Many GUI improvements, such as integration of SwingWorker in the API, table sorting and filtering, and true Swing double-buffering (eliminating the gray-area effect).
- JVM improvements include: synchronization and compiler performance optimizations, new algorithms and upgrades to existing garbage collection algorithms, and application start-up performance.
- Java 6 can be installed to Mac OS X 10.5 (Leopard) running on 64-bit (Core 2 Duo and higher) processor machines.[54] Java 6 is also supported by both 32-bit and 64-bit machines running Mac OS X 10.6
Java 5 Features
- Generic
- Metadata
- Autoboxing/unboxing
- Enumerations
- Varargs
- Enhanced for each loop
- Improved
- Static imports
- Improvements - Semantics of execution for multi-threaded Java programs
- Improvements - Automatic stub generation for RMI objects
- Improvements - Swing: New skinnable look and feel, called synth
- Improvements - The concurrency utilities in package java.util.concurrent
- Improvements - Scanner class for parsing data from various input streams and buffers