Core Java

New Features in Java 20

Java 20, released in March 2023, introduced several features and enhancements. Let us delve into Java 20 new features.

1. Java 20: Scoped Values (JEP 429)

Many Java applications consist of components or modules that require sharing data among themselves. Frequently, these modules operate on threads, necessitating the protection of shared data from unintended modifications. We traditionally employ ThreadLocal variables to facilitate data sharing among components. However, this approach presents some challenges:

  • A ThreadLocal variable is mutable, allowing both get() and set() methods on its variable type.
  • Potential memory leaks occur as the values of ThreadLocal variables persist until explicitly removed using remove() or until the thread exits, lacking a binding to the thread’s lifetime.
  • Excessive memory footprints arise when dealing with numerous threads, as child threads inherit ThreadLocal variables from parent threads, leading to memory allocation for each ThreadLocal variable.

To address these issues, Java 20 introduces Scoped Values, offering a solution for sharing data within and across threads. Scoped values present a straightforward, immutable, and inheritable option for data sharing, particularly in scenarios involving a substantial number of threads.

A ScopedValue is an immutable value accessible for reading during a defined period of a thread’s execution. Its immutability ensures secure and straightforward data sharing for a limited thread execution period without the need to pass values as method arguments.

Setting the value of a variable for the bounded thread execution period is achieved using the where() method of the ScopedValue class. Once the data is obtained through the get() method, further access is restricted.

Upon completion of a thread’s run() method, the scoped value reverts to an unbound state. Utilizing the get() method enables reading the value of a scoped-value variable within a thread.

2. Java 20: Record Patterns (JEP 432)

In JDK 19, Record Patterns were introduced as a preview feature, laying the foundation for more expressive and concise code. With Java 20, we witness an enhanced and polished version of record patterns, bringing about several improvements in this release:

  • Support for the type inference of arguments in generic record patterns has been added, contributing to more streamlined and readable code.
  • Record patterns can now be utilized in the header of an enhanced for loop, providing increased flexibility in handling data structures.
  • The support for named record patterns, allowing optional identifiers for reference, has been removed. This adjustment simplifies the syntax and usage of record patterns.

This release is centered around the goal of enabling enhanced and composable data queries through pattern matching, all while preserving the existing syntax and semantics of type patterns. The refinements in Java 20 contribute to a more robust and versatile implementation of record patterns.

3. Java 20: Pattern Matching for Switch (JEP 433)

Java 20 introduces a polished iteration of pattern matching for switch expressions and statements, focusing on refining the grammar associated with switch expressions. This feature was initially introduced in Java 17 and has undergone further enhancements in Java 18 and 19, expanding the utility and versatility of switch statements and expressions.

The key changes in this release are as follows:

  • When using a switch expression or a pattern over an enum class and no switch label is applied at runtime, Java 20 now throws a MatchException. Previously, an IncompatibleClassChangeError would be encountered.
  • There are notable improvements in the grammar related to switch labels, contributing to a more expressive and robust syntax.
  • Support for the type inference of arguments for generic record patterns in switch expressions and statements has been added. This enhancement extends to other constructs that support patterns.

These changes in Java 20 further enhance the reliability and expressiveness of switch expressions, reinforcing their role in modern Java programming.

4. Java 20: Foreign Function and Memory API (JEP 434)

Java 20 introduces further enhancements and refinements to the Foreign Function and Memory (FFM) API, building upon the improvements made in earlier Java versions. This release marks the API as a second preview, showcasing the commitment to refining its capabilities.

The Foreign Function and Memory API empowers Java developers to interact with code outside the Java Virtual Machine (JVM) and manage non-heap memory. It serves as a secure, enhanced, and entirely Java-based alternative to the Java Native Interface (JNI).

The refinements in Java 20 include:

  • Unifying the MemorySegment and MemoryAddress abstractions, enabling the determination of the range of memory addresses associated with a segment from its spatial bounds.
  • Enhancing the sealed MemoryLayout hierarchy to facilitate the utilization of pattern matching in switch expressions and statements.
  • Introducing a division of the MemorySession into Arena and SegmentScope, streamlining the sharing of segments across maintenance boundaries.

These refinements in the Foreign Function and Memory API contribute to its safety, usability, and overall effectiveness, providing Java developers with a powerful tool for managing external code and memory in a Java-centric manner.

5. Java 20: Virtual Threads (JEP 436)

Virtual threads, initially introduced as a preview feature in JEP 425 and delivered in Java 19, make a return in Java 20 with a second preview. This iteration aims to gather additional feedback and improvement suggestions from users, allowing for further refinement based on practical usage.

Designed as lightweight threads, virtual threads streamline the development, maintenance, and monitoring of high-throughput concurrent applications. Their introduction facilitates easier debugging and troubleshooting using existing JDK tools, proving particularly valuable in scaling server applications.

It’s crucial to note that the traditional Thread implementation persists, and the introduction of virtual threads does not seek to replace Java’s fundamental concurrency model.

Here are some noteworthy changes since the first preview:

  • The methods introduced in Thread—join(Duration), sleep(Duration), and threadId()—are now permanent features in Java 20.
  • Similarly, newly introduced methods in the Future for examining task state and result—state() and resultNow()—have been made permanent in Java 20.
  • ExecutorService now extends AutoCloseable, adding to its flexibility.
  • Degradations to ThreadGroup, the legacy API for grouping threads as described in JEP 425, have been made permanent in JDK 19. ThreadGroup is not suitable for grouping virtual threads.

These refinements in Java 20’s second preview of virtual threads enhance the overall stability and functionality of this feature, emphasizing its role in modern Java concurrency.

6. Java 20: Structured Concurrency (JEP 437)

Structured Concurrency, initially proposed by JEP 428 and introduced as an incubating API in JDK 19, is making a return in JDK 20 with a re-incubation. This JEP aims to reintroduce the API with minimal changes, providing an opportunity for additional feedback and refinement.

The primary objective of Structured Concurrency is to simplify multithreaded programming through the introduction of an API that organizes concurrent tasks in a structured manner. This approach enhances reliability by grouping multiple threads performing similar tasks into a cohesive unit of work. Consequently, it leads to improved error handling and facilitates thread cancellations. Moreover, it advocates for a more secure approach to concurrent programming, addressing common risks associated with thread cancellation.

Despite the re-incubation, there is one notable change in the API. The updated StructuredTaskScope now supports the inheritance of scoped values by threads created within a task scope. This enhancement enables the convenient sharing of immutable data across multiple threads.

The re-incubation of Structured Concurrency in JDK 20 underscores the commitment to refining and enhancing concurrent programming tools, providing developers with a more reliable and efficient approach to managing multithreaded tasks.

7. Java 20: Vector API (JEP 438)

The Vector API, initially proposed by JEP 338 and integrated into JDK 16 as an incubating API, continues its development with the fifth incubator release. This iteration follows multiple rounds of incubations and integrations into preceding Java versions.

The Vector API serves the purpose of expressing vector computations within Java, specifically on supported CPU architectures. A vector computation involves a sequence of operations on vectors, and the Vector API is designed to facilitate such computations more optimally compared to traditional scalar computations.

In Java 20, this release maintains the API without introducing any changes compared to Java 19. However, it includes several bug fixes and performance enhancements to ensure a more robust and efficient user experience.

Notably, the development of the Vector API is closely aligned with Project Valhalla, as it aims to incorporate enhancements from Project Valhalla in the future. This synergy reflects a commitment to evolving the Vector API in tandem with broader language improvements.

8. Conclusion

Java 20 seamlessly builds upon the success of its predecessors, incorporating advancements from past releases such as record patterns, pattern matching for switch expressions, FFM, virtual threads, and more. Additionally, it introduces a new incubating feature—scoped values—and enhances re-incubating features like structured concurrency and the Vector API.

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button