Table of Contents
2. Structured Concurrency (Preview)
3. Pattern Matching for switch (Finalized)
4. Sequenced Collections API (Preview)
5. Unnamed Variables and Patterns (Preview)
Summary: What Should You Do?
Home Java javaTutorial The Evolution of Java: What's New in Java 21

The Evolution of Java: What's New in Java 21

Jul 27, 2025 am 01:37 AM

Java 21, an LTS release, introduces major enhancements that modernize the platform. 1. Virtual Threads are now final, enabling efficient, lightweight concurrency ideal for I/O-bound tasks, allowing simple synchronous code to scale. 2. Structured Concurrency (preview) improves error handling and cancellation by treating related tasks as a unit, enhancing reliability and debuggability. 3. Pattern Matching for switch is finalized, supporting type checks and record deconstruction to reduce boilerplate and improve clarity. 4. Sequenced Collections API (preview) adds ordered collection operations like getFirst(), getLast(), and reversed() for more intuitive handling of ordered data. 5. Unnamed Variables and Patterns (preview) allow using _ for unused variables, reducing clutter and warnings. 6. Performance and security improvements include ZGC with concurrent class unloading, Vector API updates, Foreign Function & Memory API previews, and stronger cryptographic defaults. Developers should upgrade from older LTS versions, adopt virtual threads for scalable services, use pattern matching for cleaner code, and explore structured concurrency and sequenced collections for future readiness, making high-performance concurrent programming more accessible.

The Evolution of Java: What\'s New in Java 21

Java 21, released in September 2023, marks a major milestone in the evolution of the Java platform. With long-term support (LTS) status, it brings a host of new features, performance improvements, and language enhancements that make Java more modern, expressive, and efficient. Whether you're a seasoned Java developer or just catching up, here's what’s new and why it matters.

The Evolution of Java: What's New in Java 21

1. Virtual Threads (Preview → Final)

One of the most anticipated features in Java 21 is the finalization of Virtual Threads, which were introduced as a preview in Java 19 and 20.

  • What are Virtual Threads?
    They are lightweight threads managed by the JVM, not the operating system. Unlike platform threads (traditional java.lang.Thread), thousands or even millions of virtual threads can be created with minimal overhead.

    The Evolution of Java: What's New in Java 21
  • Why it matters:
    Virtual threads revolutionize how we write concurrent applications—especially server-side ones. They allow developers to write simple, synchronous code that scales like asynchronous code.

  • How to use them:

    The Evolution of Java: What's New in Java 21
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
        IntStream.range(0, 100).forEach(i -> {
            executor.submit(() -> {
                System.out.println("Task "   i   " on thread: "   Thread.currentThread());
                return i;
            });
        });
    } // executor.close() is called automatically

    This creates 100 virtual threads that run independently but consume far fewer OS resources than traditional threads.

Tip: Use virtual threads for I/O-bound tasks (like web servers or database calls), not CPU-heavy workloads.


2. Structured Concurrency (Preview)

Structured Concurrency simplifies error handling and cancellation in concurrent code by treating groups of related tasks as a single unit of work.

  • It ensures that if one thread fails, all related threads are canceled, preventing resource leaks and simplifying debugging.

  • Designed to work seamlessly with virtual threads.

  • Example:

    try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
        Future<String>  user  = scope.fork(() -> fetchUser());
        Future<Integer> order = scope.fork(() -> fetchOrder());
    
        scope.join();           // Wait for both tasks
        scope.throwIfFailed();  // Propagate any failure
    
        String theUser = user.resultNow();
        int theOrder = order.resultNow();
    }

This model enforces structured programming principles in concurrency—making code more readable and resilient.


3. Pattern Matching for switch (Finalized)

Pattern matching, which started with instanceof improvements, is now fully integrated into switch expressions and statements.

In Java 21, this feature is finalized, meaning it’s production-ready and no longer in preview.

  • You can now deconstruct data using pattern matching:

    String result = switch (obj) {
        case null          -> "null";
        case String s      -> "String: "   s;
        case Integer i     -> "Integer: "   i;
        case Point(int x, int y) when x > 0 -> "Positive point";
        case Point(int x, int y)            -> "Point: "   x   ","   y;
        default            -> "Unknown";
    };
  • Works with record patterns and type patterns.

  • Reduces boilerplate and makes code more declarative.


4. Sequenced Collections API (Preview)

Java 21 introduces a new interface hierarchy to better represent ordered collections.

  • New interface: SequencedCollection extends Collection and adds methods like:

    • getFirst(), getLast()
    • addFirst(), addLast()
    • removeFirst(), removeLast()
  • Implementations include ArrayList, LinkedHashSet, etc.

  • Also introduces SequencedMap:

    • getFirstEntry(), getLastEntry()
    • reversed() — returns a reverse-ordered view
  • Example:

    SequencedCollection<String> collection = new ArrayList<>();
    collection.add("one");
    collection.add("two");
    
    System.out.println(collection.getFirst()); // "one"
    System.out.println(collection.getLast());  // "two"
    
    SequencedMap<Integer, String> map = new LinkedHashMap<>();
    map.put(1, "first");
    map.put(2, "second");
    System.out.println(map.reversed().getFirstEntry()); // 2=second

This makes working with ordered data more intuitive and consistent.


5. Unnamed Variables and Patterns (Preview)

A small but useful addition: the ability to use _ as a placeholder for unused variables or pattern components.

  • Helps reduce warnings and improve code clarity when you don’t care about certain values.

  • Example:

    // Instead of:
    case Point(int x, int y) when x > 0 -> System.out.println("Positive x");
    
    // You can now ignore unused parts:
    case Point(int x, _) when x > 0 -> System.out.println("Positive x");
    
    // Or in lambda:
    list.forEach((_, __) -> System.out.println("Hello"));

This avoids naming dummy variables like temp, ignored, etc.


6. Performance & Security Improvements

Beyond syntax, Java 21 includes under-the-hood enhancements:

  • ZGC (Z Garbage Collector): Now has support for concurrent class unloading, reducing pause times even further.
  • Vector API (4th Incubator): Enables better utilization of SIMD instructions for high-performance computing.
  • Foreign Function & Memory API (2nd Preview): Simplifies calling native code and managing off-heap memory—eventually replacing JNI.
  • Security: Updated cryptography algorithms and stronger defaults.

These improvements make Java faster and safer, especially for large-scale systems.


Summary: What Should You Do?

  • Upgrade to Java 21 if you're on an older LTS (like Java 11 or 17)—especially for web services where virtual threads can dramatically improve throughput.
  • Start using virtual threads in new concurrent applications.
  • Embrace pattern matching for cleaner, safer code.
  • Experiment with structured concurrency and sequenced collections—they’re likely to become standard soon.

Java isn’t standing still. With Java 21, it’s becoming simpler, faster, and more expressive—without sacrificing stability.

Basically, this release is about making high-performance, concurrent programming accessible to every developer, not just experts.

The above is the detailed content of The Evolution of Java: What's New in Java 21. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1545
276
How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Building RESTful APIs in Java with Jakarta EE Building RESTful APIs in Java with Jakarta EE Jul 30, 2025 am 03:05 AM

SetupaMaven/GradleprojectwithJAX-RSdependencieslikeJersey;2.CreateaRESTresourceusingannotationssuchas@Pathand@GET;3.ConfiguretheapplicationviaApplicationsubclassorweb.xml;4.AddJacksonforJSONbindingbyincludingjersey-media-json-jackson;5.DeploytoaJakar

Java Performance Optimization and Profiling Techniques Java Performance Optimization and Profiling Techniques Jul 31, 2025 am 03:58 AM

Use performance analysis tools to locate bottlenecks, use VisualVM or JProfiler in the development and testing stage, and give priority to Async-Profiler in the production environment; 2. Reduce object creation, reuse objects, use StringBuilder to replace string splicing, and select appropriate GC strategies; 3. Optimize collection usage, select and preset initial capacity according to the scene; 4. Optimize concurrency, use concurrent collections, reduce lock granularity, and set thread pool reasonably; 5. Tune JVM parameters, set reasonable heap size and low-latency garbage collector and enable GC logs; 6. Avoid reflection at the code level, replace wrapper classes with basic types, delay initialization, and use final and static; 7. Continuous performance testing and monitoring, combined with JMH

A Developer's Guide to Maven for Java Project Management A Developer's Guide to Maven for Java Project Management Jul 30, 2025 am 02:41 AM

Maven is a standard tool for Java project management and construction. The answer lies in the fact that it uses pom.xml to standardize project structure, dependency management, construction lifecycle automation and plug-in extensions; 1. Use pom.xml to define groupId, artifactId, version and dependencies; 2. Master core commands such as mvnclean, compile, test, package, install and deploy; 3. Use dependencyManagement and exclusions to manage dependency versions and conflicts; 4. Organize large applications through multi-module project structure and are managed uniformly by the parent POM; 5.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

See all articles