I'm always excited to take on new projects and collaborate with innovative minds.

Email

contact@niteshsynergy.com

Website

https://www.niteshsynergy.com/

Java 21

Java 21 – All Features

1*DOKe-VW6OykbHaXNE2JXuw.png

 

 

String Templates (Preview)

What?
A new way to embed variables inside strings without + or String.format().

Use Case:
Better readability when building dynamic text (logs, UI messages, SQL, JSON templates).

Simple Example

String name = "John";
int age = 30;
String msg = STR."Hello, \{name}! You are \{age} years old.";
System.out.println(msg);
 

// Generating SQL dynamically
String table = "users";
String column = "email";
String value = "abc@example.com";

String sql = STR."SELECT * FROM \{table} WHERE \{column} = '\{value}'";
db.execute(sql);
 

  • Makes templated strings cleaner and less error-prone.

 

Virtual Threads (Final)

What?
Lightweight threads managed by the JVM — millions can run simultaneously.

Use Case:
Highly concurrent servers (web APIs, chat servers, microservices).

Simple Example

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
   executor.submit(() -> System.out.println("Running in a virtual thread"));
}
 

var server = HttpServer.create(new InetSocketAddress(8080), 0);
server.executor(Executors.newVirtualThreadPerTaskExecutor());
server.createContext("/api", (req, resp) -> {
   // each request handled in a virtual thread
   String result = processData(req.getRequestURI().toString());
   resp.sendResponseHeaders(200, result.length());
});
server.start();
 

  • Improves scalability with minimal code change.

 

Sequenced Collections

What?
New interfaces like SequencedCollection, SequencedSet, SequencedMap that let you easily access first/last elements.

Use Case:
Tasks where list ordering matters (log history, queues).

Simple Example

SequencedCollection<String> list = new ArrayList<>();
list.addFirst("First");
list.addLast("Last");
System.out.println(list.getFirst()); // "First"
 

Deque<String> jobQueue = new ArrayDeque<>();
jobQueue.addFirst("HIGH_PRIORITY");
jobQueue.addLast("LOW_PRIORITY");

// process urgent jobs first
while (!jobQueue.isEmpty()) {
   String job = jobQueue.removeFirst();
   process(job);
}
→ Cleaner queue/list operations.

 

Record Patterns

What?
Allows pattern matching inside instanceof and switch for record classes.

Use Case:
Destructuring data objects more easily.

 

record Point(int x, int y) {}

if (obj instanceof Point(int x, int y)) {
   System.out.println(x + ", " + y);
}
 

record Transaction(String id, double amount) {}

switch (txn) {
   case Transaction(var id, var amt) && amt > 1000 -> System.out.println("Large txn: " + id);
   default -> System.out.println("Standard txn");
}
 

→ Easier data extraction from objects.

Pattern Matching for Switch

What?
switch can match types and conditions.

Use Case:
Replacing complex if/else trees.

String result = switch (obj) {
   case String s -> "String: " + s;
   case Integer i -> "Integer: " + i;
   default -> "Unknown";
};
 

switch (event) {
   case ClickEvent c -> handleClick(c);
   case KeyEvent k && k.keyCode() == KeyEvent.ESCAPE -> handleEscape();
   default -> logUnknown(event);
}
 

→ Makes branching logic safer and more readable.

 

Scoped Values (Preview)

What?
A modern alternative to ThreadLocal, safer with virtual threads.

Use Case:
Share context (like user ID) across layers without passing everywhere.

ScopedValue<String> USER = ScopedValue.newInstance();
ScopedValue.where(USER, "admin").run(() -> {
   System.out.println(USER.get());
});
 

ScopedValue<HttpContext> HTTP_CTX = ScopedValue.newInstance();

ScopedValue.where(HTTP_CTX, ctx).run(() -> {
   handleRequest(); // can use HTTP_CTX.get() down the call stack
});
 

→ Useful in frameworks & request contexts.

 

Foreign Function & Memory API (Preview)

What?
Interact with native code (C/C++) without JNI.

Use Case:
High-performance systems, native libraries (ffmpeg, OpenCV).

Linker linker = Linker.nativeLinker();
 

MemorySegment buffer = MemorySegment.allocateNative(1024);
CLinker linker = CLinker.systemCLinker();
var printf = linker.downcallHandle(
   linker.findSymbol("printf").get(),
   MethodType.methodType(int.class, MemoryAddress.class)
);
printf.invokeExact(buffer.address());
 

Safer & faster than JNI.

 

Generational ZGC

(JEP 439)

 

What is it?

Generational Z Garbage Collector (ZGC) is an enhanced version of ZGC that separates the heap into:

  • Young Generation → short-lived objects

  • Old Generation → long-lived objects

This improves performance by collecting short-lived objects more frequently.

 

Why was it needed?

Most Java objects:

  • Live very briefly

  • Die quickly

Older ZGC treated all objects equally.
Generational ZGC optimizes this by focusing on young objects first.

 

Use Case

✔ Large-scale applications
✔ Low-latency systems
✔ Financial systems
✔ Microservices
✔ Big heap sizes (GBs or TBs)

 

Simple Example (Enable ZGC)

java -XX:+UseZGC -XX:+ZGenerational MyApp

That’s it — no code changes needed.

 

Real-World Complex Scenario

High-traffic payment system

• Millions of short-lived objects (requests, DTOs) • Few long-lived objects (caches, configs) • GC pause must be < 5 ms

Without Generational ZGC

  • Full heap scanned

  • Higher CPU usage

  • More latency spikes

With Generational ZGC

  • Young objects cleaned fast

  • Old objects scanned rarely

  • Pause time stays under 1 ms

 

Benefits

✔ Ultra-low pause times
✔ Better throughput
✔ Lower memory pressure
✔ Ideal for cloud & containers

Key Encapsulation Mechanism (KEM) API

(JEP 452)

What is it?

A new cryptography API designed to support post-quantum cryptography.

It protects encryption keys against future quantum computer attacks.

 

Why is this important?

Quantum computers can break:

  • RSA

  • Diffie-Hellman

  • ECC

KEM provides quantum-safe key exchange.

Use Case

✔ Banking & finance
✔ Government systems
✔ Secure messaging
✔ Blockchain
✔ Long-term encrypted data

Simple Example

KeyEncapsulation kem = KeyEncapsulation.getInstance("ML-KEM");

Sample Code (Key Generation)

KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM"); KeyPair kp = kpg.generateKeyPair(); PublicKey publicKey = kp.getPublic(); PrivateKey privateKey = kp.getPrivate();

 

Real-World Complex code

Secure Client-Server Communication

// Client KEM kem = KEM.getInstance("ML-KEM"); KEM.Encapsulated enc = kem.encapsulate(serverPublicKey); SecretKey sessionKey = enc.key(); // Server SecretKey sameSessionKey = kem.decapsulate(enc.encapsulation(), serverPrivateKey);

✔ Both sides now share the same secure key
✔ Resistant to quantum attacks

 

Benefits

✔ Future-proof encryption
✔ Java-native API
✔ No third-party crypto needed
✔ Enterprise-ready security

 

Unnamed Patterns & Variables

(JEP 443)

 

 What is it?

Allows you to ignore unused variables using _.

 

Why is this useful?

Before Java 21:

  • You had to create fake variable names

  • Code became noisy and confusing

Now:

  • Use _ to clearly say “I don’t care about this value”Use Case

✔ Pattern matching
✔ Records
✔ Switch expressions
✔ Cleaner code
✔ Avoid unused warnings

 

Simple  Code

if (obj instanceof Point(int x, int _)) {    System.out.println(x); }

 

 Switch Code

switch (obj) {    case String _ -> System.out.println("Some string");    case Integer i -> System.out.println(i);    default -> {} }

 

Real-World Code 

Processing API responses

record ApiResponse(int status, String body, String debugInfo) {} if (response instanceof ApiResponse(200, String body, _)) {    process(body); }

debugInfo ignored
✔ Cleaner logic
✔ Intent is very clear

 

 

 
6 min read
фев 15, 2026
By Nitesh Synergy
Share

Leave a comment

Your email address will not be published. Required fields are marked *