Java LTS Features Guide (Java 11, 17, 21, and 25)
This guide covers the major features introduced in Java 11, Java 17, Java 21, and Java 25 LTS releases, along with a detailed explanation of Virtual Threads and their differences from Platform Threads.
Java 11 Features (LTS)
Section titled “Java 11 Features (LTS)”Java 11, released in 2018, is a Long-Term Support (LTS) release focused on productivity, performance, and modern APIs.
1. New String Methods
Section titled “1. New String Methods”Java 11 introduced several useful methods to the String class.
isBlank()lines()strip()stripLeading()stripTrailing()repeat(int count)
System.out.println(" ".isBlank());
System.out.println("Hello".repeat(3));
System.out.println(" Java ".strip());2. File Read/Write Methods
Section titled “2. File Read/Write Methods”Simplified file handling.
Path path = Files.writeString(Paths.get("file.txt"), "Hello");
String content = Files.readString(path);3. HTTP Client API
Section titled “3. HTTP Client API”A modern replacement for HttpURLConnection.
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://example.com")) .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());4. var in Lambda Parameters
Section titled “4. var in Lambda Parameters”(var x, var y) -> x + yUseful when applying annotations to lambda parameters.
5. Java EE and CORBA Removal
Section titled “5. Java EE and CORBA Removal”Removed modules include:
java.xml.bindjava.xml.ws- CORBA
6. Deprecated or Removed Features
Section titled “6. Deprecated or Removed Features”- Nashorn JavaScript Engine (deprecated)
- Pack200 tools removed
7. TLS 1.3 Support
Section titled “7. TLS 1.3 Support”Improved encryption performance and security.
8. Run Java Without Compilation
Section titled “8. Run Java Without Compilation”java Hello.javaNo separate javac step is required.
9. Nest-Based Access Control
Section titled “9. Nest-Based Access Control”Improves access between nested classes.
10. Garbage Collection Improvements
Section titled “10. Garbage Collection Improvements”- Improved G1 Garbage Collector
- Better memory utilization
- Better performance
11. Flight Recorder & Mission Control
Section titled “11. Flight Recorder & Mission Control”Available without commercial licensing.
Useful for:
- Monitoring
- Profiling
- Performance analysis
Java 17 Features (LTS)
Section titled “Java 17 Features (LTS)”Java 17 is an LTS release introducing several modern language enhancements.
1. Sealed Classes
Section titled “1. Sealed Classes”Restrict which classes may extend another class.
public sealed class Vehicle permits Car, Bike {}
final class Car extends Vehicle {}
final class Bike extends Vehicle {}Benefits
Section titled “Benefits”- Controlled inheritance
- Better maintainability
- Useful with pattern matching
2. Pattern Matching for instanceof
Section titled “2. Pattern Matching for instanceof”Before Java 17
Section titled “Before Java 17”if(obj instanceof String){ String s = (String) obj; System.out.println(s.length());}Java 17
Section titled “Java 17”if(obj instanceof String s){ System.out.println(s.length());}3. Records
Section titled “3. Records”Reduce boilerplate for immutable data classes.
public record Employee(int id, String name) {}Automatically generates:
- Constructor
- Accessors
equals()hashCode()toString()
4. Enhanced Switch Expressions
Section titled “4. Enhanced Switch Expressions”String result = switch(day){ case "MONDAY", "FRIDAY" -> "Busy"; case "SUNDAY" -> "Holiday"; default -> "Normal";};5. Text Blocks
Section titled “5. Text Blocks”String json = """{ "name":"John", "age":30}""";6. Strong Encapsulation
Section titled “6. Strong Encapsulation”Internal JDK APIs are strongly encapsulated.
7. Garbage Collector Enhancements
Section titled “7. Garbage Collector Enhancements”- ZGC improvements
- Shenandoah GC support
8. Security Improvements
Section titled “8. Security Improvements”- Better cryptography
- Stronger random generators
9. Foreign Function & Memory API (Incubator)
Section titled “9. Foreign Function & Memory API (Incubator)”Allows efficient interaction with native code.
10. Apple Metal Rendering Pipeline
Section titled “10. Apple Metal Rendering Pipeline”Improved graphics rendering on macOS.
Java 17 Combined Example
Section titled “Java 17 Combined Example”public record User(int id, String name) {}
public class Main {
public static void main(String[] args) {
User user = new User(1, "Abi");
String result = switch (user.name()) { case "Abi" -> "Developer"; default -> "Unknown"; };
System.out.println(result); }}Java 21 Features (LTS)
Section titled “Java 21 Features (LTS)”Java 21 introduces Project Loom and major concurrency improvements.
1. Virtual Threads
Section titled “1. Virtual Threads”The most significant Java 21 feature.
Traditional thread:
Thread thread = new Thread(() -> { System.out.println("Platform Thread");});
thread.start();Virtual Thread:
Thread.startVirtualThread(() -> { System.out.println("Virtual Thread");});2. Pattern Matching for Switch
Section titled “2. Pattern Matching for Switch”static String check(Object obj) {
return switch (obj) {
case Integer i -> "Integer: " + i;
case String s -> "String: " + s;
default -> "Unknown"; };}3. Record Patterns
Section titled “3. Record Patterns”record Person(String name, int age) {}
if(obj instanceof Person(String name, int age)){ System.out.println(name);}4. Structured Concurrency (Preview)
Section titled “4. Structured Concurrency (Preview)”try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
// execute tasks}Benefits:
- Better error handling
- Automatic cancellation
- Cleaner concurrent programming
5. Sequenced Collections
Section titled “5. Sequenced Collections”List<Integer> list = List.of(1,2,3);
System.out.println(list.getFirst());
System.out.println(list.getLast());6. String Templates (Preview)
Section titled “6. String Templates (Preview)”String name = "Abi";
String message = STR."Hello \{name}";7. Scoped Values (Preview)
Section titled “7. Scoped Values (Preview)”ScopedValue<String> USER = ScopedValue.newInstance();8. Security Improvements
Section titled “8. Security Improvements”- Better cryptography
- Improved TLS
- Stronger key encapsulation
9. JVM Performance Improvements
Section titled “9. JVM Performance Improvements”- Faster startup
- Better JVM optimizations
- Improved garbage collection
Java 25 Features (LTS)
Section titled “Java 25 Features (LTS)”Java 25 continues Project Loom and introduces additional language and JVM enhancements.
1. Scoped Values (Final)
Section titled “1. Scoped Values (Final)”A safer replacement for ThreadLocal.
static final ScopedValue<String> USER = ScopedValue.newInstance();
ScopedValue.where(USER, "Abirami") .run(() -> {
System.out.println(USER.get());
});Benefits:
- Immutable
- Faster
- Virtual Thread friendly
2. Compact Source Files
Section titled “2. Compact Source Files”void main() {
System.out.println("Hello");}No class declaration required.
3. Flexible Constructor Bodies
Section titled “3. Flexible Constructor Bodies”Statements before super() are now allowed.
public Employee(String name) {
name = name.trim();
if(name.isEmpty()) throw new IllegalArgumentException();
super(name);}4. Module Import Declarations
Section titled “4. Module Import Declarations”import module java.sql;5. Structured Concurrency
Section titled “5. Structured Concurrency”try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<String> user = scope.fork(() -> getUser());
Future<String> orders = scope.fork(() -> getOrders());
scope.join();
return user.resultNow() + orders.resultNow();}6. Primitive Pattern Matching
Section titled “6. Primitive Pattern Matching”if(obj instanceof int i){
System.out.println(i);
}7. Key Derivation Function (KDF) API
Section titled “7. Key Derivation Function (KDF) API”Supports:
- PBKDF2
- Argon2
Useful for password hashing and key generation.
8. Compact Object Headers
Section titled “8. Compact Object Headers”Benefits:
- Lower memory usage
- Better cache utilization
- Faster object access
9. Generational Shenandoah GC
Section titled “9. Generational Shenandoah GC”- Lower pause times
- Better throughput
- Faster reclamation
10. Project Leyden Improvements
Section titled “10. Project Leyden Improvements”Adds:
- Faster startup
- Better warm-up
- Ahead-of-Time optimizations
Useful for:
- Spring Boot
- Containers
- Cloud-native applications
Java Version Comparison
Section titled “Java Version Comparison”| Version | Major Features |
|---|---|
| Java 8 | Lambda Expressions, Streams, Optional |
| Java 11 | HTTP Client, String APIs, File APIs |
| Java 17 | Records, Sealed Classes, Pattern Matching |
| Java 21 | Virtual Threads, Structured Concurrency |
| Java 25 | Scoped Values, Flexible Constructors, Compact Source Files |
Deep Dive: Virtual Threads
Section titled “Deep Dive: Virtual Threads”What are Virtual Threads?
Section titled “What are Virtual Threads?”Virtual Threads are lightweight threads introduced as part of Project Loom.
Unlike traditional Java threads, Virtual Threads are managed by the JVM rather than being permanently mapped to operating system threads.
Their purpose is to allow Java applications to efficiently support millions of concurrent tasks.
Why Virtual Threads?
Section titled “Why Virtual Threads?”Traditional Java uses Platform Threads.
1 Java Thread ↓1 OS ThreadEach OS thread consumes:
- Stack memory (~1 MB)
- Scheduling overhead
- Expensive context switching
Creating large numbers of Platform Threads leads to excessive memory usage and poor scalability.
Platform Thread Architecture
Section titled “Platform Thread Architecture”flowchart TD
A["Java Thread"] --> B["Operating System Thread"]
Virtual Thread Architecture
Section titled “Virtual Thread Architecture”flowchart TD
A["1,000,000 Virtual Threads"]
--> B["JVM Scheduler"]
B --> C["20 Platform Threads"]
C --> D["Operating System Threads"]
Creating a Platform Thread
Section titled “Creating a Platform Thread”Thread thread = new Thread(() -> {
System.out.println("Platform Thread");
});
thread.start();Creating a Virtual Thread
Section titled “Creating a Virtual Thread”Thread.startVirtualThread(() -> {
System.out.println("Virtual Thread");
});Virtual Thread Executor
Section titled “Virtual Thread Executor”try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> processOrder());
}Platform Threads vs Virtual Threads
Section titled “Platform Threads vs Virtual Threads”| Feature | Platform Thread | Virtual Thread |
|---|---|---|
| Managed By | Operating System | JVM |
| Memory | ~1 MB Stack | Much Smaller |
| Creation Cost | High | Very Low |
| Context Switching | Operating System | JVM Scheduler |
| Suitable For | CPU-bound Tasks | I/O-bound Tasks |
| Maximum Count | Thousands | Millions |
Real-World Example
Section titled “Real-World Example”Suppose an API receives 100,000 requests.
Each request:
- Calls a database
- Calls another microservice
- Waits for network responses
Platform Threads
Section titled “Platform Threads”Request 1 → Waiting DB
Request 2 → Waiting DB
Request 3 → Waiting DBEventually:
OS Thread Pool FullNew requests wait for an available thread.
Virtual Threads
Section titled “Virtual Threads”Virtual Thread 1 → Waiting DB
Virtual Thread 2 → Waiting DB
Virtual Thread 3 → Waiting DBWhen a Virtual Thread blocks on supported I/O:
- The JVM detaches (unmounts) the Virtual Thread from the Platform Thread.
- The Platform Thread immediately executes another Virtual Thread.
- When the I/O completes, the Virtual Thread is mounted again and resumes execution.
This dramatically improves scalability.
Virtual Thread Scheduling
Section titled “Virtual Thread Scheduling”sequenceDiagram
participant VT as Virtual Thread
participant JVM as JVM Scheduler
participant PT as Platform Thread
participant DB as Database
VT->>PT: Execute Task
PT->>DB: Execute Query
Note over VT: Virtual Thread is unmounted while waiting
PT->>JVM: Platform Thread becomes available
JVM->>PT: Schedule another Virtual Thread
DB-->>PT: Response
JVM->>VT: Remount Virtual Thread
VT->>PT: Continue Execution
Example
Section titled “Example”try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 100000; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(2));
return null;
});
}}When Should Virtual Threads Be Used?
Section titled “When Should Virtual Threads Be Used?”Suitable for:
- REST APIs
- Spring Boot
- Microservices
- Database operations
- Kafka consumers
- HTTP calls
- File I/O
- Network operations
When Should They Not Be Used?
Section titled “When Should They Not Be Used?”Avoid using Virtual Threads for purely CPU-intensive workloads.
for(int i = 0; i < 1_000_000_000; i++){
// Heavy computation
}Virtual Threads improve scalability for blocking operations, not CPU throughput.
Interview Answer
Section titled “Interview Answer”What are Virtual Threads and how are they different from Platform Threads?
Section titled “What are Virtual Threads and how are they different from Platform Threads?”Virtual Threads are lightweight threads managed by the JVM, introduced as part of Project Loom.
Unlike Platform Threads, which are permanently mapped one-to-one with operating system threads, Virtual Threads are scheduled by the JVM onto a much smaller pool of Platform Threads.
When a Virtual Thread blocks on supported I/O operations, it is detached from the Platform Thread, allowing that Platform Thread to execute another Virtual Thread. Once the blocking operation completes, the Virtual Thread is remounted and continues execution.
This enables applications to handle millions of concurrent tasks while significantly reducing memory usage and thread management overhead.
Spring Boot Example
Section titled “Spring Boot Example”Traditional Tomcat:
Tomcat Thread Pool (200 Threads)
↓
200 Concurrent RequestsVirtual Threads:
Virtual Threads
↓
100,000 Concurrent RequestsNote that while Virtual Threads increase request concurrency, downstream systems such as databases or external services can still become bottlenecks.
Frequently Asked Interview Questions
Section titled “Frequently Asked Interview Questions”Java 17
Section titled “Java 17”- What are Records?
- What are Sealed Classes?
- Explain Pattern Matching.
- What are Text Blocks?
Java 21
Section titled “Java 21”- What are Virtual Threads?
- Explain Structured Concurrency.
- What are Record Patterns?
- What are Scoped Values?
- What are Sequenced Collections?
Java 25
Section titled “Java 25”- What problem do Scoped Values solve?
- Explain Flexible Constructor Bodies.
- What are Compact Object Headers?
- Explain Generational Shenandoah.
- What improvements does Project Leyden bring?
Virtual Threads
Section titled “Virtual Threads”- What happens when a Virtual Thread blocks?
- How are Virtual Threads scheduled?
- What is thread pinning?
- How do Virtual Threads differ from Reactive Programming?
- Can Spring Boot use Virtual Threads?
- Are Virtual Threads suitable for Kafka consumers?
Key Takeaways
Section titled “Key Takeaways”- Java 11 modernized the JDK with improved APIs, HTTP Client, and productivity enhancements.
- Java 17 introduced modern language features such as Records, Sealed Classes, Pattern Matching, and Text Blocks.
- Java 21 brought Project Loom into production with Virtual Threads and major concurrency improvements.
- Java 25 continues Project Loom with Scoped Values, Flexible Constructor Bodies, Compact Source Files, and JVM optimizations.
- Virtual Threads dramatically improve scalability for I/O-bound applications by allowing millions of lightweight concurrent tasks while reusing a small number of Platform Threads.