Core Java

New features in Java 21

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

1. String Template (JEP-430)

String template provide a dynamic approach to string generation by substituting placeholders with variable values and computed results during runtime. This process, commonly referred to as string interpolation, enables the efficient composition of complex strings i.e. (mix the expression and code):

// After Java 21
‘Hello {your user_name}, welcome to the JavaCodeGeeks!’  

2. Library Improvements

  • Virtual Threads: JDK 21 introduces virtual threads to the Java platform, allowing tasks to be executed swiftly without consuming extensive resources and memory space.
  • Sequenced Collections: Java 21 introduces innovative approaches to working with collections, providing an interface to represent collections in a specific order. This ensures developers always have visibility into the sequence of items, allowing easy access to the first and last items. Additionally, developers can traverse the items in reverse if necessary.
  • Key Encapsulation Mechanisms (KEMs): JDK 21 introduces an API for Key Encapsulation Mechanisms (KEM), offering a secure means of storing secret keys.
  • Vector API: In Java 21, an API and vector tools are provided to achieve optimal performance in tasks such as graphics rendering or scientific calculations.

3. Z Garbage Collection (ZGC) in Java

  • Java incorporates the Z Garbage Collection (ZGC) feature, which efficiently performs resource-intensive tasks concurrently without interrupting the execution of application threads.
  • With the enhanced ZGC cleaning tool, it now effectively clears unused memory, categorizing items in the memory as ‘new’ and ‘old’ notes.
  • Consider the analogy of a computer program using memory to store and manage information. As the program runs, it generates objects akin to notes in this memory. Over time, numerous notes become unnecessary, and if not removed, they can congest the memory, similar to unused papers cluttering a desk and slowing down operations.
  • ZGC distinguishes between ‘new’ and ‘old’ notes. It operates by recognizing that newer notes are often short-lived and not be needed after a brief period. On the other hand, older notes might retain importance. Therefore, by prioritizing and cleaning up the new notes more frequently, ZGC ensures that the memory desk remains less cluttered, promoting efficiency.

4. Improved Tools for Process Management

  • Java 21 has elevated its tools, including Runtime.exec and ProcessBuilder, designed for initiating new processes, such as running a new program.
    ProcessBuilder pb = new ProcessBuilder(); 
    pb.command("ping", "www.javacodegeek.com");
    
  • For Java programs frequently initiating new processes using Runtime.exec or ProcessBuilder, this enhancement facilitates the tracking and logging of these activities.
    logger.log(System.Logger.Level.INFO, "Starting process.");
    Process process = processBuilder.start();
    
  • In applications with a logging setup, this new feature enables specific monitoring of the logger named java.lang.ProcessBuilder, ensuring detailed oversight of process-related activities.

5. Improved Emoji Handling in Java

Java has incorporated a method in the java.lang.Character class specifically designed to work with various properties of emojis, as defined by the Unicode Standard (Unicode Emoji Technical Standard) UTS#51. For instance, you can utilize the isEmoji(…) method to check whether a given code point corresponds to a unique numeric representation of a character, determining if it represents an emoji.

boolean isEmojiCharacter = Character.isEmoji('😊');

6. Improved Resource Management with HttpClient

  • The HttpClient is now AutoCloseable, allowing its usage within a try-with-resources block in Java. This enables automatic resource closure when they are no longer needed.
  • JDK 21 introduces new methods in the latest version, such as the close() method. This method waits for any ongoing requests to finish before closing, ensuring a seamless closure of the HttpClient once tasks are completed.
    HttpClient client = HttpClient.newHttpClient(); 
    client.close();
    
  • Another method, shutdown(), initiates a quick closure of the HttpClient without waiting for all tasks to conclude. The shutdownNow() method attempts an immediate shutdown of the HttpClient, even if operations are still in progress.
    HttpClient client = HttpClient.newHttpClient(); 
    client.shutdown();
    
  • awaitTerminationDuration() waits for the client to shut down within a specific time duration.
    HttpClient client = HttpClient.newHttpClient(); 
    client.shutdown(); 
    
    if (client.awaitTermination(Duration.ofMinutes(1))) { 
    	System.out.println("Terminated."); 
    } else { 
    	System.out.println("Termination in progress."); 
    }
    
  • The isTerminated() method checks whether the HttpClient has fully completed its shutdown process.
    HttpClient client = HttpClient.newHttpClient(); 
    client.shutdown(); 
    
    // ... after some time 
    if (client.isTerminated()) { 
    	System.out.println("Client has terminated."); 
    }
    

7. Enhancements in JDK 21: StringBuilder and StringBuffer

  • JDK 21 introduces additional methods to java.lang.StringBuilder and java.lang.StringBuffer.
  • The int codePoint method enables the addition of the same character multiple times to StringBuilder or StringBuffer using its Unicode number.
  • The CharSequence method allows the repeated addition of a word or phrase to StringBuilder or StringBuffer.
  • Instead of employing loops for appending repeated characters or sequences, these methods provide a superior and more concise approach to achieve the same. This results in cleaner and more maintainable code.
  • The addition of repeat methods to StringBuilder and StringBuffer streamlines and enhances the efficiency of appending repeated characters or sequences. This eliminates the need for manual loops and improves code readability.
    StringBuilder sb2 = new StringBuilder(); 
    sb2.repeat("*:", 20);  // Appends "*:*:*:*:*:*:*:*:*:*:*:*:*:*:*:*:" to sb2
    

8. Exploring Virtual Threads

Virtual threads represent a revolutionary concept in Java, offering lightweight threads with minimal footprints. This innovation significantly simplifies the process of developing, maintaining, and monitoring high-throughput concurrent systems.

For nearly three decades, Java programmers have constructed concurrent server applications using threads. In Java, a thread refers to a sequential chunk of code that executes simultaneously and generally independently of other units.

Traditionally, threads in the JDK have been implemented as wrappers around operating system (OS) threads. Unfortunately, this implementation imposes constraints on the total number of threads, as OS threads are expensive resources. This limitation makes the thread-per-request method impractical, necessitating a more efficient implementation to allow for a more abundant and scalable use of threads while maintaining harmony with the platform.

A virtual thread in Java is an instance of java.lang.Thread is not bound to a specific OS thread. It functions as a platform thread, implemented as a thin wrapper around an OS thread. The cost-effectiveness and abundance of virtual threads eliminate the need for pooling. In this paradigm, each task in the application initiates a new virtual thread. Consequently, most virtual threads are short-lived with shallow call stacks, typically executing single tasks like an HTTP client call or a JDBC query.

9. Foreign Function & Memory (FFM) API

Java programs now can interact seamlessly with data and other programs that operate outside the Java runtime, thanks to the Foreign Function and Memory API. This advancement allows calling foreign functions and accessing external memory safely. The primary goals of this API are to prioritize ease of use, performance, safety, and generality. Furthermore, it opens up the possibility of replacing the Java Native Interface (JNI) with a more advanced, pure Java development model while maintaining comparable performance to existing libraries.

The Foreign Function & Memory (FFM) API, introduced through JEP 389, serves as the consolidation of the Foreign-Memory Access API (JEPs 370, 383, and 393) and the Foreign Linker API. It introduces classes and interfaces that enable the allocation of foreign memory, manipulation and access of structured foreign memory, and the invocation of foreign functions.

10. Pattern Matching for Switches

Introduced as a preview feature in JDK 17 and further refined in JDK 18, Pattern Matching for switches has become a valuable addition to Java programming. Originally proposed by JEP 406 and later enhanced by JEP 420, this feature addresses the common need to compare multiple options for a given variable.

While Java already provides multi-way comparisons through switch statements and switch expressions (JEP 361), the conventional switch has certain limitations. It is restricted to use with integral primitive types (excluding long), their wrapped counterparts, enum types, and String values.

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

Utilizing the new pattern-matching switch, as demonstrated in the example above, employs an appropriate control construct and enhances the code’s clarity. Moreover, it is optimizable, opening up the possibility of achieving O(1) time complexity in certain cases.

11. Sequenced Collections

Sequenced collections (JEP 431) bring a new dimension to the world of Java by introducing collections with a well-defined encounter order. These collections offer uniform APIs for accessing both the first and last elements and processing elements in both forward and reverse order.

The implementation of sequenced collections involves retrofitting three new interfaces—sequenced collections, sets, and maps—into the existing collections type hierarchy. Each of these interfaces introduces new methods that streamline and enhance the development process:

  • A sequenced collection now includes a reversed() method. This method allows developers to view the collection in reversed order, facilitating the processing of elements in both directions. It also supports standard iteration operations like forEach() and stream().
  • A sequenced set incorporates addFirst(E) and addLast(E) methods. These methods efficiently position elements within the set, ensuring proper handling if an element is already present.
  • A sequenced map introduces put*(K, V) methods, mirroring the functionality of add*(E) methods in sequenced sets.

12. Empowering Java Learners with JEP 451

The new feature, introduced through JEP 451, aims to provide students with the opportunity to write single-class programs, allowing them to gradually expand their projects as their knowledge grows. Consider the traditional HelloWorld program, a fundamental example that includes features that might be overwhelming:

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

This streamlined approach allows students to gradually introduce complexity as they grasp essential concepts, eliminating the need for a simplified Java dialect specifically tailored for educational purposes.

13. Why new enhancements are essentials?

  • The addition of new features in Java is a response to the evolving software landscape, where developers encounter fresh challenges. The Java community actively incorporates feedback to introduce features that simplify modern coding, empowering developers to build more efficient Java applications.
  • These enhancements aim to boost the performance of Java platforms, ensuring that Java applications run faster, consume less memory, and exhibit greater responsiveness.
  • New features and updates play a crucial role in addressing known vulnerabilities and enhancing the overall security framework of the platform.
  • Java, with its robust and open-source nature, benefits from a collaborative community. The addition of new features often results from contributions and suggestions through Java Enhancement Proposals (JEPs).
  • In the evolving Java 21 environment, new tools, platforms, and services are introduced. These new features enhance interoperability with other technologies.
  • As JDK 21 incorporates numerous new features, outdated and inefficient ones are deprecated. The addition of new features ensures that developers have improved alternatives to deprecated features.
  • New features contribute to a more predictable and consistent interaction between different parts of the language.
  • Introducing new libraries, tools, or syntax enables developers to write code more efficiently, leading to reduced development time and minimizing potential errors.
  • JEP 452: The Key Encapsulation Mechanism (KEM) API introduces an innovative encryption technique designed to enhance security by safeguarding symmetric keys using asymmetric (public key) cryptography. Unlike conventional methods, KEM leverages the properties of public keys to derive a related symmetric key, all without the need for padding. As of now, Java lacks a standardized KEM API. Nevertheless, this technique holds significant importance in contemporary cybersecurity, providing a robust defense against cyberattacks. It is poised to become an integral part of the next generation of standard public key cryptography algorithms.

14. Conclusion

As we navigate the evolving landscape of Java programming, Java 21 emerges as a beacon of innovation and efficiency. The latest release brings forth a myriad of enhancements, ranging from improved tools for process management to the introduction of Virtual Threads and the Key Encapsulation Mechanism (KEM) API.

The advent of Virtual Threads opens up new possibilities for developers, offering a lightweight and scalable solution for concurrent systems. With its ability to execute tasks swiftly without allocating excessive resources, Virtual Threads redefines the paradigm for high-throughput applications.

Additionally, the Key Encapsulation Mechanism (KEM) API introduces a cutting-edge encryption technique, securing symmetric keys through asymmetric cryptography. This modern approach enhances security measures, reflecting Java’s commitment to staying ahead in the realm of cybersecurity.

Sequenced collections, pattern matching for switches, and the Foreign Function & Memory (FFM) API contribute to the versatility of Java 21, empowering developers with new tools and methodologies for crafting robust and efficient applications.

As we explore these features and enhancements, it becomes evident that Java 21 not only addresses the challenges faced by developers but also paves the way for a more streamlined and effective development experience. Whether you are a seasoned developer or a student embarking on a Java journey, Java 21 invites you to embrace the future of programming with its powerful and user-friendly features.

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