What is new in java 14

Alok Kumar
Sep 6, 2020 · 10 min read
Photo by Caspar Camille Rubin on Unsplash

Hello All, As a java developer we need to update our shelf about the new features, enhancement, or deprecated API of every new release of Java. JDK 14 comes plenty of new or previewing and Incubator features such as pattern matching for instanceof, Helpful NullPointerExceptions, switch expressions, Memory management API, deprecated some garbage collector algorithm, and many more.

In the Software industry, Java Developers are still using an older version of java like java8 or java7 or java6 or even older ones. Java8 has a major feature release and that is a lambda expression, Functional programming capability.

So whether we’re migrating over to Java9 or Java 11 or java13 or maybe even Java 14, Java 8 concepts and features are still very much alive in the JDK.
Here, I would like to share the important changes, enhancements, removed APIs and features, deprecated APIs and features, and other information about JDK 14.

There are several categories of new, nonfinal features

  1. A preview language or VM feature is a new feature of the Java SE Platform that is fully specified, fully implemented, and yet impermanent. It is available in a JDK feature release to provoke developer feedback based on real-world use. To compile source code with javac that uses preview features from JDK release n, use javac from JDK release n with the --enable-preview command-line option in conjunction with either the --release n or -source n command-line option. javac — enable-preview — release 14 <JavaSourceCode.java>

Here’s the list of some important and useful Java 14 features:

1. Pattern Matching for instanceof (Preview)

An instanceof in Java is a comparison operator which, given an object instance, checks whether that instance is of a specified type (class/sub-class/interface) or not. Just like other comparison operators, it returns true or false.

The following code shows how pattern matching for instanceof removes this redundant code(object casting ) by introducing a pattern variable. In Java14, the equals() method can be written as below.

@Override
public boolean equals(Object o) {
return o instanceof Monitor other &&
model.equals(other.model) &&
price == other.price;
}

Pattern variables i.e “other” is the final local variables that are declared and initialized at the same place. With other final local variables, it is possible to declare them and defer their assignment. Also, you cannot assign another value to a pattern variable since it is implicitly final. The scope of the pattern variable is limited.

2. Switch Expressions

The current design of Java’s switch the statement follows closely languages such as C and C++, and supports fall through semantics by default. The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. Here’s an example of the classic switch statement with an enum:

In the above code, the many break statements make it unnecessarily verbose, where missing break statements would mean accidental fall through.

Switch expressions were first introduced in Java 12, got an improvement in Java 13, and will be a standard feature in Java 14.

  1. Java 14 introduces a new form of switch label, “case L ->", to signify that only the code to the right of the label is to be executed if the label is matched. It also allows multiple constants per case, separated by commas.

2. We extend the switch a statement so it can be used as an expression.

3. Most switch expressions will have a single expression to the right of the "case L ->" switch label. In the event that a full block is needed, we introduce a new yield statement to yield a value, which becomes the value of the enclosing switch expression.

What’s the difference to a default return and yield?

A return statement returns control to the invoker of a method or constructor, while a yield statement transfers control by causing an enclosing switch expression to produce a specified value.

3. Record in Java14

Suppose We will have to create a data model say “Student” with attribute “name” and “id”. As developers, we are used to defining a data class, encapsulating variables to store its state. However, with a regular class, the rules are to define private instance variables to store the state of your data object, add public constructors, accessor or mutators methods, and override methods like toString(), equals(), and hashCode() from the Object class.

In Java 14, Records introduce a new type of declaration in Java, which simplifies the task of modeling your data as data. It also cuts down significantly on the boilerplate code. In Java 14 We can create a record as below.

record StudentModel(String name, int id){}

With just one line of code, the preceding example defines a record with components Name and id. By default, the compiler creates a bunch of methods for a record, like instance methods to store its state, constructors, getters (no setters-the intent to the data be immutable), and overrides toString(), equals(), and hashCode() method from the Object class.

Java compiler defines a record as a final class, a record implicitly extends the java.lang.Record class from the core Java API. For each of the components (data variables), it defines, the compiler defines a final instance variable. Interestingly, the name of the getter methods is the same as the name of the data variable (and don’t start with ‘get’). Since a record is supposed to be immutable, no setter methods are defined.

The methods toString(), hashCode() and equals() are also generated automatically for records.

We can declare static variables, static method, and nonstatic method using the same syntax as a class:

4. NUMA-Aware Memory Allocation for G1

Non-uniform memory access (NUMA) is a way of configuring a cluster of microprocessors into a multiprocessing system, so that memory can be shared locally and performance can be improved and the system’s ability extended.

To optimize memory access locality of Java server applications, There are two different Java heap configurations. The first one, NUMA-Eden, uses a NUMA-aware young generation and the original old generation of the HotSpot VM we used. The second one, NUMA-Eden+Old, uses both NUMA-aware young generation and NUMA-aware old generation. The NUMA-Eden configuration focuses on optimizing the locality of the accesses to the objects in the young
generation whereas the NUMA-Eden+Old configuration focuses on optimizing the locality of the accesses to the objects in young and old generations. The NUMAEden+Old is more likely to be more effective than the NUMA-Eden since it targets all memory accesses in the application. However, it requires gathering object access frequencies by processors at runtime.

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.

In order to allocate a new object for a mutator thread, G1 may need to allocate a new region. It will do so by preferentially selecting a free region from the NUMA node to which the current thread is bound so that the object will be kept on the same NUMA node in the young generation. If there is no free region on the same NUMA node during region allocation for a mutator then G1 will trigger a garbage collection.

5. Remove the Concurrent Mark Sweep (CMS) Garbage Collector

CMS GC was developed in response to an increasing number of applications that demand a GC with lower worst-case pause times than Serial or Parallel GC and where it is acceptable to sacrifice some application throughput to eliminate or greatly reduce the number of lengthy GC pauses.

In CMS GC, young garbage collections are similar to those of Parallel GC. They are parallel stop-the-world, meaning all Java application threads are paused during young garbage collections and the garbage collection work is performed by multiple threads. Note that you can configure CMS GC with a single-threaded young generation collector, but this option has been deprecated in Java 8 and is removed in Java 9.

CMS uses the parallel stop-the-world mark-copy algorithm in the Young Generation and concurrent mark-sweep algorithm in the Old Generation.
Young Generation — Par New Collector — mark-copy Algorithm Old Generation — CMS Collector — mark-sweep Algorithm.

Performance Issues with CMS

  1. Concurrent Mode Failure: However, if the CMS collector is unable to finish reclaiming the unreachable objects before the tenured generation fills up, or if an allocation cannot be satisfied with the available free space blocks in the tenured generation, then the application is paused and the collection is completed with all the application threads stopped.

When trying to run the Java application with -XX:+UseConcMarkSweepGC, the error message now shown states: " Ignoring option UseConcMarkSweepGC; support was removed in 14.0".

6. Helpful NullPointerExceptions

Java 14 improves the usability of NullPointerException generated by the JVM by describing precisely which variable was null.

When we execute the above program using any compiler older than java 14 , We will get the null pointer exception without any information which variable is null.

In Java14, We need to pass -XX:+ShowCodeDetailsInExceptionMessages JVM flag to enable this feature while running the application.We VM argument in intellij like this .

Now the output of the above program is as below, Now We can see which variable is null.

7. Deprecate the ParallelScavenge + SerialOld GC Combination

There is one combination of GC algorithms that we believe is very little used but requires a significant amount of maintenance effort: The pairing of the parallel young generation GC and the serial old GC . This combination must be specifically enabled by the user with the -XX:+UseParallelGC -XX:-UseParallelOldGC command line options. The only advantage of this combination compared to using a parallel GC algorithm for both the young and old generations is slightly lower total memory usage.

8. Foreign Memory Access API in Java 14

Java objects reside on the heap. However, this can occasionally lead to problems such as inefficient memory usage, low performance, and garbage collection issues. Native memory can be more efficient in these cases, but using it has been traditionally very difficult and error-prone.
Java 14 introduces the foreign memory access API to access native memory more securely and efficiently. Before the introduction of the foreign memory access API in Java, there were two main ways to access native memory in Java. These are java.nio.ByteBuffer and sun.misc.Unsafe classes. There are some limitations with these api .

  1. Incorrect use of a ByteBuffer can cause a memory leak and OutOfMemory errors. This is because an unused memory reference can prevent the garbage collector from deallocating the memory.

Foreign memory access API provides three important abstraction .

MemorySegment : A MemorySegment is used to model a contiguous memory region with given spatial and temporal bounds.Let’s create a native memory segment of 200 bytes:
MemorySegment memorySegment = MemorySegment.allocateNative(200);

MemoryAddress : MemoryAddress can be thought of as an offset within a segment.

MemoryLayout : MemoryLayout is a programmatic description of a memory segment’s contents.

9. Text Blocks

Text Blocks were introduced as a preview feature in Java 13 with the goal to allow easy creation of multiline string literals. It’s useful in easily creating HTML and JSON or SQL query strings. In Java 14, Text Blocks are still in preview with some new additions. We can now use:
tring text =”””
I am Alok \
I am from Inida \
I am working in Oracle\
“””;

There are few more features like new packaging tools, Garbage Collection mechanism for window and mac Os, Some API deprecation and many more have been introduced in java14. We can get the list of all these features of JDK 14, You can get more and more information about these features. Please go through this link .

Happy Learning … :)

Javarevisited

Medium’s largest Java publication, followed by 10000+ programmers. Follow to join our community.

Sign up for Javarevisited Newsletter

By Javarevisited

Collection of best Java articles, tutorials, courses, books, and resources from Javarevisite and its authors, Java Experts and many more.  Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Alok Kumar

Written by

I am still learning …

Javarevisited

A humble place to learn Java and Programming better.

Alok Kumar

Written by

I am still learning …

Javarevisited

A humble place to learn Java and Programming better.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store