Today we have the premiere of the long-awaited JDK 21. Therefore, this edition will focus on it.
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
- Java 21’s New (Sequenced) Collections – A video presentation from Inside Java Newscast, featuring the original JEP. It has also text suplement
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
- Garbage Collector Implementation – Generational Garbage Collection – guide from Oracle itself describing the generation hypothesis in the context of HotSpot VM.
- JEP 377: ZGC: A Scalable Low-Latency Garbage Collector – the original JEP introducing ZGC itself.
- An Introduction to ZGC: A Scalable and Experimental Low-Latency Garbage Collector – An accessible introduction to ZGC itself. Admittedly, ZGC isn’t so “experimental” anymore, but the text itself is updated regularly (last on Monday, September 18).
- An Introduction to ZGC: A Scalable and Experimental Low – Presentation from JavaOne on ZGC topic.
- Inside Java Podcast – Episode 24 “Towards Generational ZGC!” – The Official Java Podcast, describing the “kitchens” of working on Generational UGC.
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
- What good are Record Patterns in Java? An example based on Spark’s Catalyst Optimizer and it’s Tree Rewriting Rules – article with non-trivial examples.
- Data Oriented Programming in Java – text presenting the assumptions behind records, pattern matching and other new language syntax elements in Java. IMHO a must-read to better understand its evolution 🚨. It also applies to the following👇.
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
- Data Oriented Programming in Java – as in case of JEP 440, I highly encourage you to familiarize yourself with it.
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
- All together now: Spring Boot 3.2, GraalVM native images, Java 21, and virtual threads with Project Loom – Text presenting Spring’s position when it comes to Project Loom implementations.
- Helidon Níma – The first Java Framework written from the ground up to support Virtual Threads – will appear as part of Helidon 4.0.0
- Virtual Thread Support Reference in Quarkus – a description of the current Virtual Threads supports in the third of the big Java frameworks.
- What is blocking in Loom? – Text describing in detail the problem of “pinning” threads.
- Implementing Raft using Project Loom – As in the title, an example of using virtual threads to implement Raft.
- The Ultimate Guide to Java Virtual Threads – A great Virtual Threads course from Rock the JVM Blog.
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
- A beginner’s guide to Java agents – A quick introduction to the topic of Java Agents from the Java Advent Calendar (a very cool annual initiative, I wonder what they are preparing this year).
- The definitive guide to Java agents by Rafael Winterhalter – Similar thing, but heavily expanded and in video form 😃
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
- Deep dive into a post-quantum key encapsulation algorithm – an article from Cloudflare describing in accessible terms how KEM works.
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.
And finally, some additional links
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: