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.
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.

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 (traditionaljava.lang.Thread
), thousands or even millions of virtual threads can be created with minimal overhead. 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:
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
extendsCollection
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are three main differences between Callable and Runnable in Java. First, the callable method can return the result, suitable for tasks that need to return values, such as Callable; while the run() method of Runnable has no return value, suitable for tasks that do not need to return, such as logging. Second, Callable allows to throw checked exceptions to facilitate error transmission; while Runnable must handle exceptions internally. Third, Runnable can be directly passed to Thread or ExecutorService, while Callable can only be submitted to ExecutorService and returns the Future object to

Java supports asynchronous programming including the use of CompletableFuture, responsive streams (such as ProjectReactor), and virtual threads in Java19. 1.CompletableFuture improves code readability and maintenance through chain calls, and supports task orchestration and exception handling; 2. ProjectReactor provides Mono and Flux types to implement responsive programming, with backpressure mechanism and rich operators; 3. Virtual threads reduce concurrency costs, are suitable for I/O-intensive tasks, and are lighter and easier to expand than traditional platform threads. Each method has applicable scenarios, and appropriate tools should be selected according to your needs and mixed models should be avoided to maintain simplicity

JavaNIO is a new IOAPI introduced by Java 1.4. 1) is aimed at buffers and channels, 2) contains Buffer, Channel and Selector core components, 3) supports non-blocking mode, and 4) handles concurrent connections more efficiently than traditional IO. Its advantages are reflected in: 1) Non-blocking IO reduces thread overhead, 2) Buffer improves data transmission efficiency, 3) Selector realizes multiplexing, and 4) Memory mapping speeds up file reading and writing. Note when using: 1) The flip/clear operation of the Buffer is easy to be confused, 2) Incomplete data needs to be processed manually without blocking, 3) Selector registration must be canceled in time, 4) NIO is not suitable for all scenarios.

In Java, enums are suitable for representing fixed constant sets. Best practices include: 1. Use enum to represent fixed state or options to improve type safety and readability; 2. Add properties and methods to enums to enhance flexibility, such as defining fields, constructors, helper methods, etc.; 3. Use EnumMap and EnumSet to improve performance and type safety because they are more efficient based on arrays; 4. Avoid abuse of enums, such as dynamic values, frequent changes or complex logic scenarios, which should be replaced by other methods. Correct use of enum can improve code quality and reduce errors, but you need to pay attention to its applicable boundaries.

Java's class loading mechanism is implemented through ClassLoader, and its core workflow is divided into three stages: loading, linking and initialization. During the loading phase, ClassLoader dynamically reads the bytecode of the class and creates Class objects; links include verifying the correctness of the class, allocating memory to static variables, and parsing symbol references; initialization performs static code blocks and static variable assignments. Class loading adopts the parent delegation model, and prioritizes the parent class loader to find classes, and try Bootstrap, Extension, and ApplicationClassLoader in turn to ensure that the core class library is safe and avoids duplicate loading. Developers can customize ClassLoader, such as URLClassL

Javaprovidesmultiplesynchronizationtoolsforthreadsafety.1.synchronizedblocksensuremutualexclusionbylockingmethodsorspecificcodesections.2.ReentrantLockoffersadvancedcontrol,includingtryLockandfairnesspolicies.3.Conditionvariablesallowthreadstowaitfor

The key to Java exception handling is to distinguish between checked and unchecked exceptions and use try-catch, finally and logging reasonably. 1. Checked exceptions such as IOException need to be forced to handle, which is suitable for expected external problems; 2. Unchecked exceptions such as NullPointerException are usually caused by program logic errors and are runtime errors; 3. When catching exceptions, they should be specific and clear to avoid general capture of Exception; 4. It is recommended to use try-with-resources to automatically close resources to reduce manual cleaning of code; 5. In exception handling, detailed information should be recorded in combination with log frameworks to facilitate later

HashMap implements key-value pair storage through hash tables in Java, and its core lies in quickly positioning data locations. 1. First use the hashCode() method of the key to generate a hash value and convert it into an array index through bit operations; 2. Different objects may generate the same hash value, resulting in conflicts. At this time, the node is mounted in the form of a linked list. After JDK8, the linked list is too long (default length 8) and it will be converted to a red and black tree to improve efficiency; 3. When using a custom class as a key, the equals() and hashCode() methods must be rewritten; 4. HashMap dynamically expands capacity. When the number of elements exceeds the capacity and multiplies by the load factor (default 0.75), expand and rehash; 5. HashMap is not thread-safe, and Concu should be used in multithreaded
