Java 21 features
Java 21 is a long-term support (LTS) release, meaning it will receive extended support and updates. This version builds upon the experimental features of previous releases and brings several refinements. Here are the key enhancements:
Java 21 Features (Released September 2023)
1. Virtual Threads (Final)
- Provides lightweight threads for efficient concurrency management.
- Reduces overhead compared to traditional platform threads.
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { executor.submit(() -> System.out.println("Running in a virtual thread")); }
2. Structured Concurrency (Preview)
- Simplifies parallel programming and thread management.
- Ensures tasks are completed reliably, reducing concurrency bugs.
3. Pattern Matching for switch
(Final)
- Allows more expressive type matching in switch statements.
switch (obj) { case String s -> System.out.println("String: " + s); case Integer i -> System.out.println("Integer: " + i); default -> System.out.println("Unknown type"); }
4. Scoped Values (Preview)
- Provides an efficient way for threads to share data.
- Helps avoid reliance on
ThreadLocal
storage.
5. Foreign Function & Memory API (Final)
- Allows Java programs to interact with native libraries without JNI.
- Improves interoperability with external systems.
6. Sequenced Collections
- Introduces
SequencedCollection
,SequencedSet
, andSequencedMap
. - Standardizes methods like
reverse()
for collections.
7. String Templates (Preview)
- Allows inline expressions inside strings, similar to other language using The STR Template Processor The STR Template Processor performs string interpolation by iteratively replacing each embedded expression of the provided template with the stringified value of that expression. Below We’ll have an example of STR processor String template:
String name = "Java";
String message = STR."Welcome to \{name} 21!";
8. Performance and Security Improvements
- General optimizations for JVM efficiency.
- Enhanced security measures for safer execution.
Why Java 21 Matters
Being an LTS version, Java 21 is expected to be widely adopted by enterprises and long-term projects. It finalizes key features such as virtual threads, pattern matching, and foreign function API, making Java more modern and developer-friendly.