Loading...

Java 21 is GA!

September 21, 2023
2 minutes to read
Share this post:

Hi,

Java 21 has finally reached General Availability (GA) status since Tuesday 🎉

For months, I’ve taken every opportunity to talk about how virtual threads are the highlight of this release for me. For instance, in this or this old newsletter, or here on my blog.

And that hasn’t changed. I believe virtual threads are one of the most significant improvements in years. Whether everything turns out as expected remains to be seen.

But of course, there are also other features that shouldn’t go unmentioned.

Collections are expanded with new methods

New interfaces, SequencedCollection and SequencedMap, have been introduced to make it easier to access the first and last element of a collection:

interface SequencedCollection<E> extends Collection<E> {
    SequencedCollection<E> reversed();
    void addFirst(E);
    void addLast(E);
    E getFirst();
    E getLast();
    E removeFirst();
    E removeLast();
}

image.png

And then there’s Record Pattern Matching

Since Java 16, pattern matching is finally available in Java, and after an instanceof, we no longer have to cast unnecessarily. With Java 21, this feature is expanded for Records. Now, we can write something like:

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

And with switch-cases, we can also construct the following:

record Pair<T1, T2>(T1 first, T2 second) { }

public static void main(String[] args) {
    Pair<String, Object> p = new Pair<>("foo", 42);
    switch (p) {
        case Pair(String a, String b) -> System.out.println("Two strings: " + a + b);
        case Pair(String a, Integer b) -> System.out.println("String and Integer: " + a + b);
        default -> throw new IllegalStateException("Unexpected value: " + p);
    }
}

But please, instead of my example, work with polymorphism and strictly typed classes. But it’s always good to have options.

And less boilerplate!

The Generational ZGC promises better performance

Especially short-lived objects can be cleaned up more quickly. This makes garbage collector runs more efficient - in terms of both CPU and memory.

Nice change - but I’m not on fire for it 😉

Otherwise, there are a lot of new preview features, like the new option to declare the main method without a surrounding class. I haven’t looked at most of them in detail yet.

Upcoming conferences will be all about the new features, and I’m curious to see what else is hidden in detail. I’ll definitely share some of it with you here!

Rule the Backend,

~ Marcus

Top