JDK14 - What's new features in Java 14
Java 14 (Java SE 14) and its Java Development Kit 14 (JDK 14) open-source has been released on
17 March 2020 with significant number of Java Enhancement Proposals (JEPs) in version 14. (Even
more JEPs than Java 12 and 13 combined)
Java 14 Release Date :
17 March 2020
JAVA 14 addresses a total of 16 main enhancements/changes (JEPs) ranging from the Java language support to the latest APIs for ongoing JDK flight recorder monitoring. The entire feature list consists of:
- Pattern Matching for instanceof (Preview)
- Non-Volatile Mapped Byte Buffers (Incubator)
- Helpful NullPointerExceptions
- Switch Expressions (Standard)
- Packaging Tool (Incubator)
- NUMA-Aware Memory Allocation for G1
- JFR Event Streaming
- Records (Preview)
- Deprecate the Solaris and SPARC Ports
- Remove the Concurrent Mark Sweep (CMS) Garbage Collector
- ZGC on macOS (experimental)
- ZGC on Windows (experimental)
- Deprecate the ParallelScavenge + SerialOld GC Combination
- Remove the Pack200 Tools and API
- Text Blocks (Second Preview)
- Foreign-Memory Access API (Incubator)
-
Pattern Matching for instanceof: Instanceof is used to check whether the object
reference is and instance of given Type or not, and return boolean flag. It improves the
programming language for Java
with pattern matching for the operator instanceOf. Pattern matching allows for the more
clear and efficient expression of common logic in a system, namely the conditional
removal of components from objects.
Before - Without this featureif (obj instanceof String) { String str = (String) obj; // need to declare and cast again the object .. str.contains(..) .. }else{ str = .... }
With this feature enhancements
More example:if (!(obj instanceof String str)) { .. str.contains(..) .. // no need to declare str object again with casting } else { .. str.... }
if (obj instanceof String str && str.length() > 5) {.. str.contains(..) ..} if (obj instanceof String str || str.length() > 5) {.. str.contains(..) ..}
NOTE: instanceOf will only match, when object is not null and then only it assigned to str. The use of pattern matching in instanceof should reduce the overall number of explicit casts in Java programs.
Non-Volatile Mapped Byte Buffers
: To give high level overview, all you know Java NIO (New IO) File API is there since JDK 1.4, FileChannel with MappedByteBuffer to load the portion of file data into virtual memory, then new enhancement has been introduced called Path. Path is the interface that replaces java.io.File class as the representation of a file or a directory when we work in Java NIO.
Now Java 14 has done enhancement in MappedByteBuffer to load the portion of file data in non-volatile memory (NVM). Non volatile memory or non volatile storage is a computer memory, where data would not lost/deleted even if power is turned off like ROM (Read Only Memory), Flash memory, storage devices like hard disk etc. And in case of volatile it don't keep data if power is turned off like RAM. The only API change required is a new enumeration employed by FileChannel clients to request mapping of a file located on an NVM-backed file system rather than a conventional, file storage system.
Risks and Assumptions
This implementation allows for management of NVM as an off-heap resource via a ByteBuffer. A related enhancement, JDK-8153111 , is looking at the use of NVM for heap data. It may also be necessary to consider use of NVM to store JVM metadata. These different modes of NVM management may turn out to be incompatible or, possibly, just inappropriate when used in combination. The proposed API can only deal with mapped regions up to 2GB. It may be necessary to revise the proposed implementation so that it conforms to changes proposed in JDK-8180628 to overcome this restriction.Helpful NullPointerExceptions
: Improvement in NullPointerExceptions exception message generated by JVM. It will be helpful information to developers and support staff about the premature termination of a program. Since NPEs can occur almostwhere in a program, it is generally impractical to attempt to catch and recover from them. As a result, developers rely on the JVM to pinpoint the source of an NPE when it actually occurs. For example, suppose an NPE occurs in this code: a.i = 99;
Suppose an NPE occurs in this code:Exception in thread "main" java.lang.NullPointerException at Prog.main(Prog.java:5)
The filename and line number do not pinpoint exactly which variable was null. Was it a or b or c? Now JDK14 JEP has improved this exception to be thrown as given below to know exact which variable was null.a.b.c.i = 99;
However there are some Risk. The null-detail message may contain variable names from the source code. Exposing this information might be considered a security risk.Exception in thread "main" java.lang.NullPointerException: Cannot read field 'c' because 'a.b' is null. at Prog.main(Prog.java:5)
Switch Expressions (Standard)
Java 14 has extended switch statement, which can be used as an expression with help of arrow (->), and now can yield/return the value. This was a preview language feature in JDK 12 and JDK 13.
EXAMPLE-1
Before Java 14switch (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 14 enhancements
EXAMPLE-2switch (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); }
Before Java 14int 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 14 enhancementsint 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; } };
Packaging Tool (Incubator)
It is a packaging feature designed to ease the installation process, which depends on various dependencies. Sometimes it's not enough to provide a single JAR file; it must provide an installable kit appropriate for the local/native. A packaging tool can also help to fill the gaps left by other technologies.
The jpackage tool bundles a Java application into a platform-specific package containing all the dependencies required. As a set of ordinary JAR files or as a collection of modules. The supported platform-specific package formats are:
- Linux: deb and rpm
- macOS: pkg and dmg
- Windows: msi and exe
NUMA-Aware Memory Allocation for G1
Non-uniform memory access (NUMA) is a way of configuring cluster of microprocessor into a multiprocessing system, so that memory can be shared locally and performance can be improved and the system's ability extended.
Java 14 has provided the NUMA-aware memory allocation feature to improve G1 performance on large machines.
G1's heap is organized as a collection of fixed-size regions. A region is typically a set of physical pages, although when using large pages (via -XX:+UseLargePages) several regions may make up a single physical page.
If the+XX:+UseNUMA
option is specified then, when the JVM is initialized, the regions will be evenly spread across the total number of available NUMA nodes.JFR Event Streaming
Java 14 provided an API, by which the data collected by the JDK Flight Recorder (JFR) will continuous monitor in-process and out-of-process applications.
Same set of events can be recorded as in the non-streaming way, with overhead less than 1% if possible. Therefore, event streaming would be performed at the same time as non-streaming.
The package
jdk.jfr.consumer
, in modulejdk.jfr
, is extended with functionality to subscribe to events asynchronously.Records (Preview)
This is a preview language feature in JDK 14. It is used to compact the class declaration syntax with record.
We need to write a lot of low-value, repetitive code to write a simple data carrier class responsibly: constructors, accessors, equals(), hashCode(), toString(), etc. To avoid this repetitive code, Java is planned to use record.
Example:
Before:
Java 14 with recordsfinal class Scale { public final int x; public final int y; public Scale(int x, int y) { this.x = x; this.y = y; } // state-based implementations of equals, hashCode, toString // nothing else
Limitation of using records:record Scale(int x, int y) { }
- Records cannot extend any other class, and cannot declare instance fields other than the private final fields which correspond to components of the state description.
- Records are implicitly final, and cannot be abstract, such limitations underline that a record's API is entirely defined by its state definition and can not be modified by another class or record later.
- The components of a record are implicitly final.
Deprecate the Solaris and SPARC Ports
Deprecate Solaris / SPARC, Solaris / x64, and Linux / SPARC ports in order to remove them in the future.
By removing support for these ports, contributors in the OpenJDK community will be able to accelerate the development of new features to move the platform forward.
The following should result in an attempt to configure a Solaris and/or SPARC
The new$ bash ./configure ... checking compilation type... native configure: error: The Solaris and SPARC ports are deprecated and may be removed in a future release. \ Use --enable-deprecated-ports=yes to suppress this error. configure exiting with result code 1 $
--enable-deprecated-ports=yes
configuration option will suppress the error and proceed.
Configuring a build for Solaris and SPARC (including Solaris / SPARC, Solaris / x64, Linux / SPARC) will issue the error / warning.$ bash ./configure --enable-deprecated-ports=yes ... checking compilation type... native configure: WARNING: The Solaris and SPARC ports are deprecated and may be removed in a future release. ... Build performance summary: * Cores to use: 32 * Memory limit: 96601 MB
Remove the Concurrent Mark Sweep (CMS) Garbage Collector
Java 14 has removed the Concurrent Mark Sweep (CMS) garbage collector.
This update will deactivate CMS compilation, remove content of the gc / cms directory from the source tree, and remove CMS-only options.
The following warning message will result in the attempt to use CMS via the -XX:+UseConcMarkSweepGC option
VM will keep running using the default collector.Java HotSpot(TM) 64-Bit Server VM warning: Ignoring option UseConcMarkSweepGC; \ support was removed in <version>
JEP 364 - ZGC on macOS
JEP 364 is practically same as JEP 365. Only JEP 364 offers the Z Garbage Collector (ZGC) for MacOS. It port the ZGC garbage collector to macOS. Part of the JEP is also the collector's functionality for freeing unused device memory, as stated in JEP 351, this has been since since Java 13. The macOS implementation of ZGC contains two parts:
- Support for multi-mapping memory on macOS.
- Support in ZGC for discontiguous memory reservations.
JEP 365 - ZGC garbage collector on Windows
JEP 365 is practically same as JEP 364. Only JEP 365 offers the Z Garbage Collector (ZGC) for Windows.
Most of the ZGC code base is platform independent and does not require Windows-specific changes. Supporting Windows 10 and Windows Server older than version 1803 is not a goal, since older versions lack the necessary API required for memory reservations.The Windows implementation of ZGC needs the following work:
- Support for multi-mapping memory The use of colored pointers by ZGC requires multi-mapping support, so that the same physical memory can be accessed from multiple locations in the process address space. On Windows, paging-file backed memory provides an identity (a handle) to physical memory that is unrelated to the virtual address where it is mapped Using this identity allows ZGC to map the same physical memory to multiple locations.
- Support for mapping paging-file backed memory into a reserved address space The Windows memory management API is not as flexible as POSIX's mmap/munmap, particularly when it comes to mapping file backed memory into a previously reserved address space region. For this purpose ZGC will use the Windows concept of address space placeholders. In version 1803 of Windows 10 and Windows Server the placeholder concept was introduced. ZGC support will not be implemented to older versions of Windows.
- Support for mapping and unmapping arbitrary parts of the heap ZGC's heap layout requires support for mapping and unmapping arbitrary heap granules in combination with its dynamic sizing (and re-sizing) of heap pages. This requirement in combination with Windows address space placeholders requires special attention because placeholders must be explicitly split / coalesced by the program rather than automatically split / coalesced by the operating system (as with Linux).
- Support for committing and uncommitting arbitrary parts of the heap ZGC will dynamically commit and uncommit physical memory while the Java program runs. In order to support these operations, the physical memory will be divided into, and backed by, multiple paging-file segments. Each paging-file segment corresponds to a ZGC heap granule, and can be committed and uncommitted independently of other segments.
JEP 366 - Deprecate the ParallelScavenge + SerialOld GC Combination
JEP 366 involves garbage collector, and it targets to deprecate the combination of the Parallel Scavenge and Serial Old garbage collection algorithms. Besides depreciating the combination -XX:+UseParallelGC-XX :- UseParallelOldGC, the -XX: UseParallelOld GC option is also deprecated as it is used to deselect the old-generation parallel GC, thereby enabling the serial old generation GC. As a result any intentional use of the option UseParallelOldGC will show deprecation warning.
JEP 367: Remove the Pack200 Tools and API
Pack200 is a JAR file compression scheme implemented by JSR 200 in Java SE 5.0.
Remove the pack200 and unpack200 tools and the pack200 API from the java.util.jar package. These tools and APIs have been deprecated for removal in Java SE 11 with the express intention of removing them in a future release. In the JDK feature release for which this JEP is eventually intended, 3 types will be removed in the java. Base module previously annotated with @Deprecated(forRemoval = true):
- java.util.jar.Pack200
- java.util.jar.Pack200.Packer
- java.util.jar.Pack200.Unpacker
JEP 368: Text Blocks (Second 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 Block
String 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 Block
String 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.
In mid-2019, JDK 13 introduced Text Block as Preview feature, which then re-visited by adding below two new escape sequences in Java 14.
Two new escape sequences are newlines (line-terminator) denoted by \ and second is for white space (single space) denoted by /s.
Newlines Example:
White Space or Single Space Example:// Without Text Block String literal = "two escape sequences first is for newlines " + "and, second is to signify white space " + "or single space."; // With the \<line-terminator> escape sequence this could be expressed as: String text = """ two escape sequences first is for newlines \ and, second is to signify white space \ or single space.\ """;
// Using \s at the end of each line in this example guarantees that each line is exactly six characters long String colors = """ aaa\s bbb\s ccc\s """;
JEP 370: Foreign-Memory Access API (Incubator)
Many popular Java libraries and programs have access to foreign memory, such as Ignite, MapDB, Memcached, and Netty's ByteBuf API. In doing so, they can avoid the cost and unpredictability associated with garbage collection (especially when maintaining large caches), share memory across multiple processes, and serialize and deserialize memory content by mapping files into memory (via, e.g., mmap). However, the Java API does not have a suitable solution for accessing foreign memory.
With JEP 370, an effective Java API is to be introduced in the Java 14 JDK, which enables Java applications to safely and efficiently access foreign memory stored outside the Java heap. The foreign-memory access API introduces three main abstractions: MemorySegment, MemoryAddress and MemoryLayout.
Take a look at our Suggested Posts :
Quick glance on earlier Java Versions Features :
Java 13 Features - JDK 13
- Dynamic CDS Archives
- ZGC: Uncommit Unused Memory
- Reimplement the Legacy Socket API
- Switch Expressions (Preview)
- Text Blocks (Preview)
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