1. Overview

In this article, we’ll discuss the new features and enhancements that have been added to Java 21.

Java 21, released on September 19, 2023, is the latest LTS version after the previous Java 17.

2. List of JEPs

Next, we’ll talk about the most notable enhancements, also called Java Enhancement Proposals (JEP), the new version of the language introduced.

2.1. Record Patterns (JEP 440)

Record patterns were included in Java 19 and Java 20 as preview features. Now, with Java 21, they are out of the preview and include some refinements.

This JEP extends the existing pattern-matching feature to destructure the record class instances, which enables writing sophisticated data queries. Moreover, this JEP adds support for nested patterns for more composable data queries.

For example, we can write code more concisely:

record Point(int x, int y) {}
    
public static int beforeRecordPattern(Object obj) {
    int sum = 0;
    if(obj instanceof Point p) {
        int x = p.x();
        int y = p.y();
        sum = x+y;
    }
    return sum;
}
    
public static int afterRecordPattern(Object obj) {
    if(obj instanceof Point(int x, int y)) {
        return x+y;
    }
    return 0;
}

As a consequence, we can also nest records within records and deconstruct them:

enum Color {RED, GREEN, BLUE}
record ColoredPoint(Point point, Color color) {}
record RandomPoint(ColoredPoint cp) {}
public static Color getRamdomPointColor(RandomPoint r) {
    if(r instanceof RandomPoint(ColoredPoint cp)) {
        return cp.color();
    }
    return null;
}

Above, we access the .color() method directly from ColoredPoint.

2.2. Pattern Matching for switch (JEP 441)

Initially introduced in JDK 17, Pattern matching for the switch was refined in JDK 18, 19, and 20 and improved further in JDK 21.

The main goal of this feature is to allow patterns in switch case labels and improve the expressiveness of switch statements and expressions. Besides, there is also an enhancement to handle NullPointerException by allowing a null case label.

Let’s explore this with an example. Suppose we have an Account class:

static class Account{
    double getBalance(){
       return 0;
    }
}

We extend this into various types of accounts, each having its method for calculating the balance:

static class SavingsAccount extends Account {
    double getSavings() {
        return 100;
    }
}
static class TermAccount extends Account {
    double getTermAccount() {
        return 1000;
    } 
}
static class CurrentAccount extends Account {
    double getCurrentAccount() {
        return 10000;
    } 
}

Before Java 21, we can use the below code to get the balance:

static double getBalanceWithOutSwitchPattern(Account account) {
    double balance = 0;
    if(account instanceof SavingsAccount sa) {
        balance = sa.getSavings();
    }
    else if(account instanceof TermAccount ta) {
        balance = ta.getTermAccount();
    }
    else if(account instanceof CurrentAccount ca) {
        balance = ca.getCurrentAccount();
    }
    return balance;
}

The above code isn’t very expressive as we have a lot of noise with the ifelse cases. With Java 21, we can leverage patterns in case labels to write the same logic more concisely:

static double getBalanceWithSwitchPattern(Account account) {
    double result = 0;
    switch (account) {
        case null -> throw new RuntimeException("Oops, account is null");
        case SavingsAccount sa -> result = sa.getSavings();
        case TermAccount ta -> result = ta.getTermAccount();
        case CurrentAccount ca -> result = ca.getCurrentAccount();
        default -> result = account.getBalance();
    };
    return result;
}

To confirm what we wrote is correct, let’s prove this with a test:

SwitchPattern.SavingsAccount sa = new SwitchPattern.SavingsAccount();
SwitchPattern.TermAccount ta = new SwitchPattern.TermAccount();
SwitchPattern.CurrentAccount ca = new SwitchPattern.CurrentAccount();

assertEquals(SwitchPattern.getBalanceWithOutSwitchPattern(sa), SwitchPattern.getBalanceWithSwitchPattern(sa));
assertEquals(SwitchPattern.getBalanceWithOutSwitchPattern(ta), SwitchPattern.getBalanceWithSwitchPattern(ta));
assertEquals(SwitchPattern.getBalanceWithOutSwitchPattern(ca), SwitchPattern.getBalanceWithSwitchPattern(ca));

So, we just rewrote a switch more concisely.

A pattern case label also supports matching against expressions for the same label. For example, suppose we need to process an input string that contains a simple “Yes” or “No“:

static String processInputOld(String input) {
    String output = null;
    switch(input) {
        case null -> output = "Oops, null";
        case String s -> {
            if("Yes".equalsIgnoreCase(s)) {
                output = "It's Yes";
            }
            else if("No".equalsIgnoreCase(s)) {
                output = "It's No";
            }
            else {
                output = "Try Again";
            }
        }
    }
    return output;
}

Again, we can see that writing ifelse logic can get ugly. Instead, in Java 21, we can use when clauses along with case labels to match the label’s value against an expression:

static String processInputNew(String input) {
    String output = null;
    switch(input) {
        case null -> output = "Oops, null";
        case String s when "Yes".equalsIgnoreCase(s) -> output = "It's Yes";
        case String s when "No".equalsIgnoreCase(s) -> output = "It's No";
        case String s -> output = "Try Again";
    }
    return output;
}

2.3. String Literal (JEP 430)

Java offers several mechanisms for composing strings with string literals and expressions. Some of these are String concatenation, StringBuilder class, String class format() method, and the MessageFormat class.

Java 21 introduces string templates. These complement Java’s existing string literals and text blocks by coupling literal text with template expressions and template processors to produce the desired results.

Let’s see an example:

String name = "Baeldung";
String welcomeText = STR."Welcome to \{name}";
System.out.println(welcomeText);

The above code snippet prints the text “Welcome to Baeldung“.

String Templates

In the above text, we have a template processor (STR), a dot character, and a template that contains an embedded expression (\{name}). At runtime, when the template processor evaluates the template expression, it combines the literal text in the template with the values of the embedded expression to produce the result.

The STR is one of Java’s template processors, and it is automatically imported into all Java source files. Java also offers FMT and RAW template processors.

2.4. Virtual Threads (JEP 444)

Virtual threads were initially introduced to the Java language as a preview feature in Java 19 and further refined in Java 20. Java 21 introduced some new changes.

Virtual threads are lightweight threads with the purpose of reducing the effort of developing high-concurrent applications. Traditional threads, also called platform threads, are thin wrappers around OS threads. One of the major issues with platform threads is that they run the code on the OS thread and capture the OS thread throughout its lifetime. There is a limit to the number of OS threads, and this creates a scalability bottleneck.

Like platform threads, a virtual thread is also an instance of java.lang.Thread class, but it isn’t tied to a specific OS thread. It runs the code on a specific OS thread but does not capture the thread for an entire lifetime. Therefore, many virtual threads can share OS threads to run their code.

Let us see the use of the virtual thread with an example:

try(var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.rangeClosed(1, 10_000).forEach(i -> {
        executor.submit(() -> {
            System.out.println(i);
            try {
                Thread.sleep(Duration.ofSeconds(1));
            } 
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    });
}

In the above code snippet, we’re using the static newVirtualThreadPerTaskExecutor() method. This executor creates a new virtual thread for each task, so in the above example, we create 10,000 virtual threads.

Java 21 introduced two notable changes to the virtual threads:

  • Virtual threads now always support thread-local variables.
  • Virtual threads are created through the Thread.Builder APIs are also monitored through their lifetime and observable in the new thread dump

2.5. Sequenced Collections (JEP 431)

In the Java collection framework, no collection type represents a sequence of elements with a defined encountered order.  For instance, List and Deque interfaces define an encounter order, but their common super type Collection doesn’t. In the same way, Set doesn’t define an encounter order, but subtypes such as LinkedHashSet or SortedSet do.

Java 21 introduced three new interfaces to represent sequenced collections, sequenced sets, and sequenced maps.

A sequenced collection is a collection whose elements have a defined encounter order. It has first and last elements, and the elements between them have successors and predecessors.  A sequenced set is a set that is a sequenced collection with no duplicate elements. A sequenced map is a map whose entries have a defined encountered order.

The following diagram shows the retrofitting of the newly introduced interfaces in the collection framework hierarchy:

Sequenced Collections

2.6. Key Encapsulation Mechanism API (JEP 452)

Key encapsulation is a technique to secure symmetric keys using asymmetric keys or public key cryptography.

The traditional approach uses a public key to secure a randomly generated symmetric key. However, this approach requires padding, which is difficult to prove secure.

A key encapsulation mechanism (KEM) uses the public key to derive the symmetric key that doesn’t require any padding.

Java 21 has introduced a new KEM API to enable applications to use KEM algorithms.

3. Conclusion

In this article, we discussed a few notable changes delivered in Java 21.

We discussed record patterns, pattern matching for switches, string templates, sequenced collections, virtual threads, string templates, and the new KEM API.

Other enhancements and improvements are spread across JDK 21 packages and classes. However, this article should be a good starting point for exploring Java 21’s new features.

As always, the source code for this article is available over on GitHub.