”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > Java 功能:详细了解新 LTS 版本中最重要的变化

Java 功能:详细了解新 LTS 版本中最重要的变化

发布于2024-07-29
浏览:584

Another LTS Java release is already here, bringing some exciting changes and improvements. Let’s analyze the most important Java 21 features, check out how they work in practice, and try to predict their significance for the future of this technology.

Since the Java platform adopted a six-month release cycle, we’ve moved past the perennial questions such as “Will Java die this year?” or “Is it worth migrating to the new version?”. Despite 28 years since its first release, Java continues to thrive and remains a popular choice as the primary programming language for many new projects.

Java 17 was a significant milestone, but Java 21 has now taken 17’s place as the next long-term support release (LTS). It’s essential for Java developers to stay informed about the changes and new features this version brings. Inspired by my colleague Darek, who detailed Java 17 features in his article, I’ve decided to discuss JDK 21 in a similar fashion.

JDK 21 comprises a total of 15 JEPs (JDK Enhancement Proposals). You can review the complete list on the official Java site. In this article, I’ll highlight several Java 21 JEPs that I believe are particularly noteworthy. Namely:

  1. String Templates
  2. Sequenced Collections
  3. Pattern Matching for switch and Record Patterns
  4. Virtual Threads

Without further delay, let’s delve into the code and explore these updates.

String Templates (Preview)

The Spring Templates feature is still in preview mode. To use it, you have to add –enable-preview flag to your compiler args. However, I’ve decided to mention it despite its preview status. Why? Because I get very irritated every time I have to write a log message or sql statement that contains many arguments or decipher which placeholder will be replaced with a given arg. And Spring Templates promise to help me (and you) with that.

As JEP documentation says, the purpose of Spring Templates is to “simplify the writing of Java programs by making it easy to express strings that include values computed at run time”.

Let’s check if it really is simpler.

The “old way” would be to use the formatted() method on a String object:

var msg = "Log message param1: %s, pram2: %s".formatted(p1, p2);

Now, with StringTemplate.Processor (STR), it looks like this:

var interpolated = STR."Log message param1: \{p1}, param2: \{p2}";

With a short text like the one above, the profit may not be that visible – but believe me, when it comes to big text blocks (jsons, sql statements), named parameters will help you a lot.

Sequenced collections

Java 21 introduced a new Java Collection Hierarchy. Look at the diagram below and compare it to what you probably have learned during your programming classes. You’ll notice that three new structures have been added (highlighted by the green color).

Java features: A detailed look at the most important changes in the new LTS release
Source: JEP 431

Sequenced collections introduce a new built-in Java API, enhancing operations on ordered datasets. This API allows not only convenient access to the first and last elements of a collection but also enables efficient traversal, insertion at specific positions, and retrieval of sub-sequences. These enhancements make operations that depend on the order of elements simpler and more intuitive, improving both performance and code readability when working with lists and similar data structures.

This is the full listing of the SequencedCollection interface:

public interface SequencedCollection extends Collection {
   SequencedCollection reversed();
   default void addFirst(E e) {
       throw new UnsupportedOperationException();
   }
   default void addLast(E e) {
       throw new UnsupportedOperationException();
   }
   default E getFirst() {
       return this.iterator().next();
   }
   default E getLast() {
       return this.reversed().iterator().next();
   }
   default E removeFirst() {
       var it = this.iterator();
       E e = it.next();
       it.remove();
       return e;
   }
   default E removeLast() {
       var it = this.reversed().iterator();
       E e = it.next();
       it.remove();
       return e;
   }
}

So, now, instead of:

var first = myList.stream().findFirst().get();
var anotherFirst = myList.get(0);
var last = myList.get(myList.size() - 1);

We can just write:

var first = sequencedCollection.getFirst();
var last = sequencedCollection.getLast();
var reversed = sequencedCollection.reversed();

A small change, but IMHO it’s such a convenient and usable feature.

Pattern Matching and Record Patterns

Because of the similarity of Pattern Matching for switch and Record Patterns, I will describe them together. Record patterns are a fresh feature – they have been introduced in Java 19 (as a preview). On the other hand, Pattern Matching for switch is kinda a continuation of the extended instanceof expression. It brings in new possible syntax for switch statements which lets you express complex data-oriented queries more easily.

Let’s forget about the basics of OOP for the sake of this example and deconstruct the employee object manually (employee is a POJO class).

Before Java 21, It looked like this:

if (employee instanceof Manager e) {
   System.out.printf("I’m dealing with manager of %s department%n", e.department);
} else if (employee instanceof Engineer e) {
   System.out.printf("I’m dealing with %s engineer.%n", e.speciality);
} else {
   throw new IllegalStateException("Unexpected value: "   employee);
}

What if we could get rid of the ugly instanceof? Well, now we can, thanks to the power of Pattern Matching from Java 21:

switch (employee) {
   case Manager m -> printf("Manager of %s department%n", m.department);
   case Engineer e -> printf("I%s engineer.%n", e.speciality);
   default -> throw new IllegalStateException("Unexpected value: "   employee);
}

While talking about the switch statement, we can also discuss the Record Patterns feature. When dealing with a Java Record, it allows us to do much more than with a standard Java class:

switch (shape) { // shape is a record
   case Rectangle(int a, int b) -> System.out.printf("Area of rectangle [%d, %d] is: %d.%n", a, b, shape.calculateArea());
   case Square(int a) -> System.out.printf("Area of square [%d] is: %d.%n", a, shape.calculateArea());
   default -> throw new IllegalStateException("Unexpected value: "   shape);
}

As the code shows, with that syntax, record fields are easily accessible. Moreover, we can put some additional logic to our case statements:

switch (shape) {
   case Rectangle(int a, int b) when a  System.out.printf("Incorrect values for rectangle [%d, %d].%n", a, b);
   case Square(int a) when a  System.out.printf("Incorrect values for square [%d].%n", a);
   default -> System.out.println("Created shape is correct.%n");
}

We can use similar syntax for the if statements. Also, in the example below, we can see that Record Patterns also work for nested records:

if (r instanceof Rectangle(ColoredPoint(Point p, Color c),
                          ColoredPoint lr)) {
   //sth
}

Virtual Threads

The Virtual Threads feature is probably the hottest one among all Java 21 – or at least one the Java developers have waited the most for. As JEP documentation (linked in the previous sentence) says, one of the goals of the virtual threads was to “enable server applications written in the simple thread-per-request style to scale with near-optimal hardware utilization”. However, does this mean we should migrate our entire code that uses java.lang.Thread?

First, let’s examine the problem with the approach that existed before Java 21 (in fact, pretty much since Java’s first release). We can approximate that one java.lang.Thread consumes (depending on OS and configuration) about 2 to 8 MB of memory. However, the important thing here is that one Java Thread is mapped 1:1 to a kernel thread. For simple web apps which use a “one thread per request” approach, we can easily calculate that either our machine will be “killed” when traffic increases (it won’t be able to handle the load) or we’ll be forced to purchase a device with more RAM, and our AWS bills will increase as a result.

Of course, virtual threads are not the only way to handle this problem. We have asynchronous programming (frameworks like WebFlux or native Java API like CompletableFuture). However, for some reason – maybe because of the “unfriendly API” or high entry threshold – these solutions aren’t that popular.

Virtual Threads aren’t overseen or scheduled by the operating system. Rather, their scheduling is handled by the JVM. While real tasks must be executed in a platform thread, the JVM employs so-called carrier threads — essentially platform threads — to “carry” any virtual thread when it is due for execution. Virtual Threads are designed to be lightweight and use much less memory than standard platform threads.

The diagram below shows how Virtual Threads are connected to platform and OS threads:

Java features: A detailed look at the most important changes in the new LTS release

So, to see how Virtual Threads are used by Platform Threads, let’s run code that starts (1 number of CPUs the machine has, in my case 8 cores) virtual threads.

var numberOfCores = 8; //
final ThreadFactory factory = Thread.ofVirtual().name("vt-", 0).factory();
try (var executor = Executors.newThreadPerTaskExecutor(factory)) {
   IntStream.range(0, numberOfCores   1)
           .forEach(i -> executor.submit(() -> {
               var thread = Thread.currentThread();
               System.out.println(STR."[\{thread}]  VT number: \{i}");
               try {
                   sleep(Duration.ofSeconds(1L));
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }));
}

Output looks like this:

[VirtualThread[#29,vt-6]/runnable@ForkJoinPool-1-worker-7]  VT number: 6
[VirtualThread[#26,vt-4]/runnable@ForkJoinPool-1-worker-5]  VT number: 4
[VirtualThread[#30,vt-7]/runnable@ForkJoinPool-1-worker-8]  VT number: 7
[VirtualThread[#24,vt-2]/runnable@ForkJoinPool-1-worker-3]  VT number: 2
[VirtualThread[#23,vt-1]/runnable@ForkJoinPool-1-worker-2]  VT number: 1
[VirtualThread[#27,vt-5]/runnable@ForkJoinPool-1-worker-6]  VT number: 5
[VirtualThread[#31,vt-8]/runnable@ForkJoinPool-1-worker-6]  VT number: 8
[VirtualThread[#25,vt-3]/runnable@ForkJoinPool-1-worker-4]  VT number: 3
[VirtualThread[#21,vt-0]/runnable@ForkJoinPool-1-worker-1]  VT number: 0

So, ForkJonPool-1-worker-X Platform Threads are our carrier threads that manage our virtual threads. We observe that Virtual Threads number 5 and 8 are using the same carrier thread number 6.

The last thing about Virtual Threads I want to show you is how they can help you with the blocking I/O operations.

Whenever a Virtual Thread encounters a blocking operation, such as I/O tasks, the JVM efficiently detaches it from the underlying physical thread (the carrier thread). This detachment is critical because it frees up the carrier thread to run other Virtual Threads instead of being idle, waiting for the blocking operation to complete. As a result, a single carrier thread can multiplex many Virtual Threads, which could number in the thousands or even millions, depending on the available memory and the nature of tasks performed.

Let’s try to simulate this behavior. To do this, we will force our code to use only one CPU core, with only 2 virtual threads – for better clarity.

System.setProperty("jdk.virtualThreadScheduler.parallelism", "1");
System.setProperty("jdk.virtualThreadScheduler.maxPoolSize", "1");
System.setProperty("jdk.virtualThreadScheduler.minRunnable", "1");

Thread 1:

Thread v1 = Thread.ofVirtual().name("long-running-thread").start(
       () -> {
           var thread = Thread.currentThread();
           while (true) {
               try {
                   Thread.sleep(250L);
                   System.out.println(STR."[\{thread}] - Handling http request ....");
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
       }
);

Thread 2:

Thread v2 = Thread.ofVirtual().name("entertainment-thread").start(
       () -> {
           try {
               Thread.sleep(1000L);
           } catch (InterruptedException e) {
               throw new RuntimeException(e);
           }
           var thread = Thread.currentThread();
           System.out.println(STR."[\{thread}] - Executing when 'http-thread' hit 'sleep' function");
       }
);

Execution:

v1.join();
v2.join();

Result:

[VirtualThread[#21,long-running-thread]/runnable@ForkJoinPool-1-worker-1] - Handling http request ....
[VirtualThread[#21,long-running-thread]/runnable@ForkJoinPool-1-worker-1] - Handling http request ....
[VirtualThread[#21,long-running-thread]/runnable@ForkJoinPool-1-worker-1] - Handling http request ....
[VirtualThread[#23,entertainment-thread]/runnable@ForkJoinPool-1-worker-1] - Executing when 'http-thread' hit 'sleep' function
[VirtualThread[#21,long-running-thread]/runnable@ForkJoinPool-1-worker-1] - Handling http request ....
[VirtualThread[#21,long-running-thread]/runnable@ForkJoinPool-1-worker-1] - Handling http request ....
[VirtualThread[#21,long-running-thread]/runnable@ForkJoinPool-1-worker-1] - Handling http request ....
[VirtualThread[#21,long-running-thread]/runnable@ForkJoinPool-1-worker-1] - Handling http request ....
[VirtualThread[#21,long-running-thread]/runnable@ForkJoinPool-1-worker-1] - Handling http request ....
[VirtualThread[#21,long-running-thread]/runnable@ForkJoinPool-1-worker-1] - Handling http request ....

We observe that both Virtual Threads (long-running-thread and entertainment-thread) are being carried by only one Platform Thread which is ForkJoinPool-1-worker-1.

To summarize, this model enables Java applications to achieve high levels of concurrency and scalability with much lower overhead than traditional thread models, where each thread maps directly to a single operating system thread. It’s worth noting that virtual threads are a vast topic, and what I’ve described is only a small fraction. I strongly encourage you to learn more about the scheduling, pinned threads and the internals of VirtualThreads.

Summary: The future of the Java programming language

The features described above are the ones I consider to be the most important in Java 21. Most of them aren’t as groundbreaking as some of the things introduced in JDK 17, but they’re still very useful, and nice to have QOL (Quality of Life) changes.

However, you shouldn’t discount other JDK 21 improvements either – I highly encourage you to analyze the complete list and explore all the features further. For example, one thing I consider particularly noteworthy is the Vector API, which allows vector computations on some supported CPU architectures – not possible before. Currently, it’s still in the incubator status/experimental phase (which is why I didn’t highlight it in more detail here), but it holds great promise for the future of Java.

Overall, the advancement Java made in various areas signals the team’s ongoing commitment to improving efficiency and performance in high-demand applications.

If you’re interested in Java, be sure to check out some of our other articles:

  1. Java 17 features: A comparison between versions 8 and 17. What has changed over the years?
  2. JVM Kubernetes: Optimizing Kubernetes for Java Developers
  3. Project Valhalla – Java on the path to better performance
  4. Advanced Java interview questions: A guide for 2023

Java features FAQ

Here are answers to some common questions regarding JDK 21, as well as Java native interface and features.

What is Java SE?

Java SE (Java Platform, Standard Edition) is a fundamental platform for developing and deploying Java applications on desktops and servers.

What is the Foreign Function and Memory API?

It’s a preview feature that lets Java programs interoperate with data and code outside the Java runtime. The API enables Java programs to call native libraries and process native data more safely than in the case of JNI. The API is a tool for safely accessing foreign memory and code, and efficiently invoking foreign functions.

How to write Java code well?

One of the key aspects is code review (you can use AI code review tools to make this process a bit less time-consuming).

What is dynamic loading in Java?

Dynamic loading in Java refers to loading classes or resources at runtime, rather than during the initial program startup.

What is structured concurrency?

Structured concurrency in Java is an approach that organizes concurrent processes in a controlled manner, aiming to enhance the maintainability, reliability, and observability of multithreaded code.

版本声明 本文转载于:https://dev.to/aroso1991/java-21-features-a-detailed-look-at-the-most-important-changes-in-the-new-lts-release-90o?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • Item 避免使用其他类型更合适的字符串
    Item 避免使用其他类型更合适的字符串
    1。避免使用字符串替代其他数据类型: 字符串旨在表示文本,但经常被误用来表示数字、枚举或聚合结构。 如果数据本质上是数字,请使用 int、float 或 BigInteger 等类型,而不是 String。 String age = "30"; // incorreto int age = 30;...
    编程 发布于2024-11-02
  • 如何使用sync.WaitGroup防止Go并发死锁?
    如何使用sync.WaitGroup防止Go并发死锁?
    解决 Goroutines 死锁在这种情况下,您在 Go 并发代码中遇到了死锁错误。让我们深入研究这个问题并提供一个有效的解决方案。该错误是由于生产者和消费者的行为不匹配而发生的。在生产者函数中实现的生产者在有限的时间内在通道 ch 上发送值。然而,存在于主函数中的消费者无限期地运行,无休止地尝试从...
    编程 发布于2024-11-02
  • 如何处理文本文件中的 Unicode 文本:无错误编写的完整指南
    如何处理文本文件中的 Unicode 文本:无错误编写的完整指南
    文本文件中的 Unicode 文本:无错写作综合指南从 Google 文档中提取的编码数据可能具有挑战性,尤其是当遇到需要转换为 HTML 使用的非 ASCII 符号时。本指南提供了处理 Unicode 文本并防止编码错误的解决方案。最初,在数据检索期间将所有内容转换为 Unicode 并将其写入文...
    编程 发布于2024-11-02
  • EchoAPI 与 Insomnia:结合实例进行综合比较
    EchoAPI 与 Insomnia:结合实例进行综合比较
    作为一名全栈开发人员,我知道拥有一流的工具来调试、测试和记录 API 是多么重要。 EchoAPI 和 Insomnia 是两个出色的选项,每个选项都有自己独特的特性和功能。让我带您了解这些工具,比较它们的功能和优点,给您一些实际示例,并帮助您决定何时使用 EchoAPI 或 Insomnia。 ...
    编程 发布于2024-11-02
  • 出发时间和持续时间|编程教程
    出发时间和持续时间|编程教程
    介绍 本实验旨在测试您对 Go 的时间和持续时间支持的理解。 时间 下面的代码包含如何在 Go 中使用时间和持续时间的示例。但是,代码的某些部分丢失了。您的任务是完成代码,使其按预期工作。 Go编程语言基础知识。 熟悉 Go 的时间和持续时间支持。 $ go run...
    编程 发布于2024-11-02
  • 起重面试问答
    起重面试问答
    1. JavaScript 中什么是提升? 答案: 提升是执行上下文创建阶段为变量和函数分配内存的过程。在此过程中,为变量分配了内存,并为变量分配了值 undefined。对于函数,整个函数定义存储在内存中的特定地址,并且对其的引用放置在该特定执行上下文中的堆栈上。 ...
    编程 发布于2024-11-02
  • 了解 JavaScript 中的文档对象模型 (DOM)
    了解 JavaScript 中的文档对象模型 (DOM)
    你好,神奇的 JavaScript 开发者? 浏览器提供了一个称为文档对象模型 (DOM) 的编程接口,它允许脚本(特别是 JavaScript)与网页布局进行交互。网页的文档对象模型 (DOM) 是一种分层树状结构,它将页面的组件排列成对象,由浏览器在加载时创建。借助此范例,文档...
    编程 发布于2024-11-02
  • 开始使用 SPRING BATCH 进行编程
    开始使用 SPRING BATCH 进行编程
    Introduction Dans vos projets personnels ou professionnels, Il vous arrive de faire des traitements sur de gros volumes de données. Le traite...
    编程 发布于2024-11-02
  • 使用 CSS 让您的 Github 个人资料脱颖而出
    使用 CSS 让您的 Github 个人资料脱颖而出
    以前,自定义 Github 个人资料的唯一方法是更新图片或更改名称。这意味着每个 Github 配置文件看起来都一样,自定义它或脱颖而出的选项很少。 从那时起,您可以选择使用 Markdown 创建自定义部分。您可以包括您的简历、您的兴趣和爱好,让您的个人资料反映您的身份。这是任何人在访问您的个人资...
    编程 发布于2024-11-02
  • TypeScript 实用程序类型:增强代码可重用性
    TypeScript 实用程序类型:增强代码可重用性
    TypeScript 提供内置实用程序类型,允许开发人员有效地转换和重用类型,使您的代码更加灵活和 DRY。在本文中,我们将探讨关键实用程序类型,例如 Partial、Pick、Omit 和 Record,以帮助您将 TypeScript 技能提升到新的水平。 Partial:使所有属性可选 部分实...
    编程 发布于2024-11-02
  • 电报 window.open(url, &#_blank&#);在ios上工作很奇怪
    电报 window.open(url, &#_blank&#);在ios上工作很奇怪
    我正在制作一个电报机器人,我想添加将一些信息从小型应用程序转发到聊天的选项。我决定使用 window.open(url, '_blank');在我在 iPhone 上尝试之前它一直运行良好。我没有转发,而是分享(这是一件大事,我正好需要转发一条消息)。我有一些如何处理它的想法,但它们...
    编程 发布于2024-11-02
  • 谁是前端开发人员?
    谁是前端开发人员?
    当今互联网上每个网站或平台的用户界面部分都是前端开发人员工作的结果。他们参与创建用户友好的界面,确保网站的外观和功能。但到底谁是前端开发人员呢?我简单解释一下。 用户看到的部分是前端 打开网站时首先看到的是网页界面:颜色、按钮、文字、动画。这都是由前端开发人员创建的。前端是网站或应用...
    编程 发布于2024-11-02
  • 如何使用保留的 CSS 样式将 HTML 内容另存为 PDF?
    如何使用保留的 CSS 样式将 HTML 内容另存为 PDF?
    使用 CSS 将 HTML 内容保存为 PDF在 Web 开发中,即使将内容导出为不同格式,保持视觉美观也至关重要。当尝试将 HTML 元素另存为 PDF 时,这可能会带来挑战,因为 CSS 样式可能会在转换过程中丢失。对于必须在保存的 PDF 中保留 CSS 的情况,请考虑使用以下方法:创建新窗口...
    编程 发布于2024-11-02
  • 为什么使用 Print_r() 时要向 DateTime 对象添加幻像属性?
    为什么使用 Print_r() 时要向 DateTime 对象添加幻像属性?
    Print_r() 更改 DateTime 对象Print_r() 向 DateTime 对象添加属性,从而在调试期间启用自省。此行为是 PHP 5.3 中引入的内部功能的副作用,它将幻像公共属性分配给转储到文本的实例。要避免这些属性引起的错误,请改用反射。然而,不建议寻找这些属性,因为它们没有在类...
    编程 发布于2024-11-02
  • C 语言的数据结构和算法:适合初学者的方法
    C 语言的数据结构和算法:适合初学者的方法
    在 C 语言中,数据结构和算法用于组织、存储和操作数据。数据结构:数组:有序集合,使用索引访问元素链表:通过指针链接元素,支持动态长度栈:先进后出 (FILO) 原则队列:先进先出 (FIFO) 原则树:分级组织数据算法:排序:按特定顺序排序元素搜索:在集合中查找元素图形:处理节点和边之间的关系实战...
    编程 发布于2024-11-02

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3