JVM

A one-sentence summary of each new JEP from JDK 21 – JVM Weekly vol. 149

Today we have the premiere of the long-awaited JDK 21. Therefore, this edition will focus on it.

Article cover

Today’s topic could only be one. The release of JDK 21.

The official blog post can be found here, and the official stream of the announcement is available here. However, I have a little bit more for you.

Due to the multitude of new features, I’m unable to delve into each one extensively, hence I will describe each function in a single sentence and provide a code snippet (for the stable APIs). Regular readers may be familiar with this type of explanation, but to avoid appearing lazy – for nearly all stable functionalities, I’ve included a collection of additional resources to help you comprehend each individual features better.

So without further ado, let’s get started, as we have a lot to cover anyway.

Stable

431: Sequenced Collections

In the case of ordered collections, a consistent interface has been introduced for retrieving the first and last elements, as well as reversing the sequence.

interface SequencedCollection<E> extends Collection<E> {
    // new method
    SequencedCollection<E> reversed();
    // methods promoted from Deque
    void addFirst(E);
    void addLast(E);
    E getFirst();
    E getLast();
    E removeFirst();
    E removeLast();
}

Additional Materials


439: Generational ZGC

Since the likelihood of a GC needing to “clean up” decreases with the lifetime of an object, having a different pipeline for short-lived and long-lived objects is standard in the GC, and now it’s coming to the ZGC as well.

Additional Materials


440: Record Patterns

Records can be effortlessly deconstructed, enabling the extraction of specific fields from them and their use in pattern matching (another JEP).

if (obj instanceof Point(int x, int y)) {
    System.out.println(x+y);
}

Additional Materials


441: Pattern Matching for switch

The capability to utilize switch for pattern matching, inclusive of sophisticated options.

static String formatterPatternSwitch(Object obj) {
    return switch (obj) {
        case Integer i -> String.format("int %d", i);
        case Long l    -> String.format("long %d", l);
        case Double d  -> String.format("double %f", d);
        case String s  -> String.format("String %s", s);
        default        -> obj.toString();
    };
}

Additional Materials


444: Virtual Threads

The introduction to the JVM of the concept of threads managed managed not by the operating system, but by the virtual machine itself.

Thread.builder().virtual().factory();

Additional Materials


449: Deprecate the Windows 32-bit x86 Port for Removal


451: Prepare to Disallow the Dynamic Loading of Agents

In order to enhance the security of Java, the developers intend to restrict in the future the loading of specific categories of Virtual Machine Agents, unless a special flag is specified.

Additional Materials


452: Key Encapsulation Mechanism API

Incorporating a standard API into Java that allows the use of a technique known as KEM, which is used, among other things, in quantum cryptography algorithms.

Additional Materials


Discover more IT content selected for you
In Vived, you will find articles handpicked by devs. Download the app and read the good stuff!

phone newsletter image

Preview

430: String Templates (Preview)

Java provides the capability to generate blocks of text, offering enhanced power and security compared to string interpolation.

JSONObject doc = JSON_VALIDATE."""
    {
        "name":    \{name},
        "phone":   \{phone},
        "address": \{address}
    };
    """;

445: Unnamed Classes and Instance Main Methods (Preview)

The Launch Protocol in Java has been modified to allow the creation of significantly simplified Java classes, primarily for educational use.

void main() {
    System.out.println("Hello, World!");
}

442: Foreign Function & Memory API (Third Preview)

Implementing typed interoperability with programs written in C, and potentially other compiled languages in the future, as well as native operating system memory.


443: Unnamed Patterns and Variables (Preview)

Introduction to the wildcard _ language, used when we don’t want to define a specific expected value/type in pattern matching, and also as a hint to linterers when we know that a declared variable is unnecessary.

if(r instanceof Point(_, int y))


453: Structured Concurrency (Preview)

A collection of structures designed to handle threads, not just virtual ones, and particularly potential errors.

try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
        Supplier<String>  user  = scope.fork(() -> findUser());
        Supplier<Integer> order = scope.fork(() ->fetchOrder());

        scope.join().throwIfFailed();

        return new Response(user.get(), order.get());
    }

446: Scoped Values (Preview)

An alternative to ThreadLocal, primarily designed for virtual threads.

final static ScopedValue<...> V = ScopedValue.newInstance();
ScopedValue.where(V, <value>).run(() -> {  V.get() });

Incubation

448: Vector API (Sixth Incubator)

Waiting for Valhalle APIs that enable vector operations, made available by modern processors.


Discover more IT content selected for you
In Vived, you will find articles handpicked by devs. Download the app and read the good stuff!

phone newsletter image

The launch of the new JDK version was followed by a stream:

One of these includes an in-depth study from the Inside Java YouTube channel, where Nicolai Parlog elaborates on each of the JEPs in a detailed 20-minute video.

Furthermore, the past several weeks have witnessed the launch of an #RoadTo21 video series on the official Java channel, presenting a particular features with more details.

Nicolai has also published the text Modern Java in Action. This provides a comprehensive overview of how all these new features can be utilized in a practical application example.

If you’re looking for something more concise, e.g for a friend who holds an antiquated view of Java, this presents a chance for me to introduce one of my preferred programming channels on YouTube. If you enjoy a jovial, ‘meme-like’ style of explanation, then Fireship is certainly worth checking out. The channel primarily features brief videos, typically less than five minutes in length.

The author concentrates on the most pertinent topics in the programming universe. It’s consistently an excellent method for me to stay current with updates from fields beyond my primary expertise, such as emerging programming languages or advancements like vector databases.

I emphasize this as a video focusing on JDK 21 has been recently launched on the Fireship channel, and I recommend you to check if this format is suitable for you as well. In my view, it’s worth trying it out:

Next week, we’ll discuss the concurrent launches of JDK 21: JavaFX and GraalVM as these also recently had a public release of a new version. Additionally, we might witness a surge of publications about new language features in the coming week. You can find a transcript of the stream below: