Whatโs New in Java 24 (LTS) - Complete Guide
Java 24 was released on March 18, 2025, marking another significant milestone in Javaโs evolution. This Long Term Support (LTS) release brings substantial improvements across language features, performance, security, and developer experience.
๐ฏ Key Highlights
- 16 major JEPs (JDK Enhancement Proposals) including new language features and runtime improvements
- Enhanced pattern matching with primitive types support
- Quantum-resistant cryptography with ML-KEM and ML-DSA algorithms
- Virtual threads performance improvements with synchronized method optimizations
- Experimental compact object headers for reduced memory footprint
- Stream Gatherers API for custom intermediate operations
๐ New Language Features (Preview)
1. Primitive Types in Patterns (Second Preview - JEP 488)
Enhanced pattern matching now supports primitive types in all contexts:
// instanceof with primitives
if (value instanceof int i && i > 0) {
System.out.println("Positive integer: " + i);
}
// Switch expressions with primitives
String result = switch (number) {
case int i when i > 100 -> "Large: " + i;
case int i when i > 0 -> "Small positive: " + i;
case 0 -> "Zero";
default -> "Negative: " + number;
};
2. Flexible Constructor Bodies (Third Preview - JEP 492)
Constructors can now include statements before super() or this() calls:
public class SafeClass {
private final String value;
public SafeClass(String input) {
// Validation before super() call
Objects.requireNonNull(input, "Input cannot be null");
String processed = input.trim().toLowerCase();
super(); // Now allowed after statements
this.value = processed;
}
}
3. Module Import Declarations (Second Preview - JEP 494)
Simplified module imports for better library reuse:
import module java.base; // Import all exported packages
import module java.logging;
// Now you can use classes without individual imports
Logger logger = Logger.getLogger("MyApp");
4. Simple Source Files and Instance Main Methods (Fourth Preview - JEP 495)
Streamlined entry points for beginners:
// Simple main method without static
void main() {
System.out.println("Hello, Java 24!");
}
// Or with arguments
void main(String[] args) {
if (args.length > 0) {
System.out.println("Hello, " + args[0]);
}
}
๐ง Performance and Runtime Improvements
Compact Object Headers (Experimental - JEP 450)
Reduces object header size from 96-128 bits to 64 bits on 64-bit architectures:
# Enable compact headers
java -XX:+UnlockExperimentalVMOptions -XX:+UseCompactObjectHeaders MyApp
# Generate CDS archive with compact headers
java -Xshare:dump -XX:+UnlockExperimentalVMOptions -XX:+UseCompactObjectHeaders
Benefits:
- Reduced heap memory usage
- Improved deployment density
- Better data locality and cache performance
Virtual Threads Synchronization (JEP 491)
Virtual threads no longer pin to platform threads when using synchronized:
// Previously would pin virtual thread to platform thread
// Now releases platform thread for other virtual threads
public synchronized void criticalSection() {
// Long-running synchronized operation
processData();
}
G1 Late Barrier Expansion (JEP 475)
Simplified G1 garbage collector implementation with improved compilation pipeline.
Ahead-of-Time Class Loading & Linking (JEP 483)
Significantly improved startup times by caching loaded and linked classes:
# Monitor application during run and cache classes
java -XX:+UnlockExperimentalVMOptions -XX:+EnableAOTClassLoading MyApp
๐ New APIs and Libraries
1. Stream Gatherers (JEP 485)
Custom intermediate operations for Stream API:
import java.util.stream.Gatherer;
// Custom gatherer for batching
List<List<String>> batched = stream
.gather(Gatherer.ofSequential(
() -> new ArrayList<String>(),
Gatherer.Integrator.of((batch, item, downstream) -> {
batch.add(item);
if (batch.size() == 3) {
downstream.push(new ArrayList<>(batch));
batch.clear();
}
return true;
})
))
.toList();
2. Class-File API (JEP 484)
Standard API for parsing, generating, and transforming Java class files:
import java.lang.classfile.*;
// Parse and transform class files
ClassFile classFile = ClassFile.of();
byte[] transformedBytes = classFile.parse(originalBytes)
.transform(ClassTransform.endHandler(clb -> {
// Add custom method or field
clb.withMethod("newMethod", MethodTypeDesc.of(CD_void), ACC_PUBLIC,
mb -> mb.withCode(cb -> {
cb.return_();
}));
}));
3. Key Derivation Function API (Preview - JEP 478)
Cryptographic key derivation support:
import javax.crypto.KDF;
// PBKDF2 key derivation
KDF kdf = KDF.getInstance("PBKDF2WithHmacSHA256");
kdf.init(DerivationSpec.builder()
.algorithm("PBKDF2WithHmacSHA256")
.salt(salt)
.iterationCount(10000)
.keyLength(32)
.build());
SecretKey derivedKey = kdf.deriveKey("myPassword".toCharArray());
๐ Enhanced Security Features
1. Quantum-Resistant Cryptography
ML-KEM (Module-Lattice-Based Key Encapsulation - JEP 496)
// Generate ML-KEM key pair
KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM");
kpg.initialize(MLKEMParameterSpec.ml_kem_768());
KeyPair keyPair = kpg.generateKeyPair();
// Key encapsulation
KEM kem = KEM.getInstance("ML-KEM");
KEM.Encapsulator encapsulator = kem.newEncapsulator(keyPair.getPublic());
KEM.Encapsulated encapsulated = encapsulator.encapsulate();
ML-DSA (Module-Lattice-Based Digital Signature - JEP 497)
// Generate ML-DSA key pair
KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA");
kpg.initialize(MLDSAParameterSpec.ml_dsa_65());
KeyPair keyPair = kpg.generateKeyPair();
// Digital signature
Signature sig = Signature.getInstance("ML-DSA");
sig.initSign(keyPair.getPrivate());
sig.update(data);
byte[] signature = sig.sign();
2. Security Manager Permanently Disabled (JEP 486)
The Security Manager has been permanently disabled and removed from the Java Platform specification.
3. JNI Usage Warnings (JEP 472)
Enhanced warnings for JNI usage to prepare for future restrictions:
# Applications using JNI will see warnings
java -Djava.security.manager=disallow MyApp
๐งช Preview and Incubator APIs
1. Scoped Values (Fourth Preview - JEP 487)
Thread-safe data sharing with better performance than ThreadLocal:
public class RequestContext {
private static final ScopedValue<String> USER_ID = ScopedValue.newInstance();
public static void handleRequest(String userId) {
ScopedValue.where(USER_ID, userId)
.run(() -> {
// USER_ID is available to all methods in this scope
processRequest();
});
}
private static void processRequest() {
String currentUser = USER_ID.get(); // No casting needed
// Process with user context
}
}
2. Structured Concurrency (Fourth Preview - JEP 499)
Simplified concurrent programming with structured task management:
try (var scope = StructuredTaskScope.ShutdownOnFailure()) {
Supplier<String> user = scope.fork(() -> fetchUser(userId));
Supplier<List<String>> orders = scope.fork(() -> fetchOrders(userId));
scope.join(); // Wait for both tasks
scope.throwIfFailed(); // Handle any failures
// Both tasks completed successfully
return new UserProfile(user.get(), orders.get());
}
3. Vector API (Ninth Incubator - JEP 489)
SIMD operations for high-performance computing:
import jdk.incubator.vector.*;
static final VectorSpecies<Float> SPECIES = FloatVector.SPECIES_256;
public void vectorAdd(float[] a, float[] b, float[] result) {
int length = a.length;
int loopBound = SPECIES.loopBound(length);
for (int i = 0; i < loopBound; i += SPECIES.length()) {
FloatVector va = FloatVector.fromArray(SPECIES, a, i);
FloatVector vb = FloatVector.fromArray(SPECIES, b, i);
va.add(vb).intoArray(result, i);
}
}
๐ Updated Libraries and Standards
1. Unicode 16.0 Support
- 154,998 total characters (5,185 new characters)
- 7 new scripts: Garay, Gurung Khema, Kirat Rai, Ol Onal, Sunuwar, Todhri, Tulu-Tigalari
- Updated Bidi and Normalization support
2. Enhanced Reader API
New factory method for efficient character sequence reading:
// More efficient than StringReader for some cases
Reader reader = Reader.of("Hello, Java 24!");
StringBuilder content = new StringBuilder();
reader.transferTo(new StringWriter());
3. Process API Improvements
Duration-based wait methods:
Process process = new ProcessBuilder("long-running-command").start();
// New Duration-based timeout
boolean finished = process.waitFor(Duration.ofMinutes(5));
if (!finished) {
process.destroyForcibly();
}
๐๏ธ Removed Features
Deprecated and Removed
- GTK 2 support removed - GTK 3 is now the minimum requirement on Linux
- JDK 1.1 timezone behavior for EST, MST, HST removed
- Various legacy java command options removed:
-t,-tm,-Xfuture,-checksource,-cs,-noasyncgc - JMX serialization compatibility with pre-JDK 5 versions removed
Deprecated for Future Removal
- jstatd tool - RMI-based monitoring tool
- jrunscript tool - JavaScript execution tool
- jdk.jsobject module - Moving to JavaFX
- Various java command options:
-verbosegc,-noclassgc,-verify,-verifyremote,-ss,-ms,-mx
๐ ๏ธ Developer Tools Enhancements
1. jar Tool Improvements
Enhanced extraction capabilities:
# Keep existing files during extraction
jar xkf myapp.jar
# Extract to specific directory
jar -xf myapp.jar -C /target/directory/
# Combined options
jar --extract --keep-old-files --file myapp.jar --dir /target/
2. jcmd Virtual Thread Monitoring
New commands for virtual thread diagnostics:
# Monitor virtual thread scheduler
jcmd <pid> Thread.vthread_scheduler
# Monitor I/O pollers
jcmd <pid> Thread.vthread_pollers
3. jpackage WiX Support
Enhanced Windows packaging with WiX Toolset v4 and v5 support:
# Automatically detects and uses newest WiX version
jpackage --input input-dir --main-jar myapp.jar --type msi
โก Performance Improvements
1. SHA3 MessageDigest Performance
- 6-27% performance improvement depending on message length
- 30-40% additional improvement on AVX-512 capable platforms
2. Direct Memory Management
Internal temporary direct buffers no longer counted against MaxDirectMemorySize limit.
3. TLS Performance
- New
jdk.tls.server.newSessionTicketCountproperty for TLS 1.3 resumption tickets - Improved HTTP/2 flow control error reporting
๐ง Configuration and System Properties
New Properties
# TLS resumption tickets count (0-10, default: 1)
-Djdk.tls.server.newSessionTicketCount=2
# HTTP header size limits (default: 393216 bytes)
-Djdk.http.maxHeaderSize=524288
# XML extension functions (default: false in Java 24)
-Djdk.xml.enableExtensionFunctions=true
# Disable compact object headers warnings
-XX:+UnlockExperimentalVMOptions -XX:+UseCompactObjectHeaders
Security Properties
# Include other security property files
include /path/to/additional/security.properties
# Disable TLS_RSA cipher suites (new default)
jdk.tls.disabledAlgorithms=TLS_RSA_*, ...
# Entrust CA distrust policy
jdk.security.caDistrustPolicies=ENTRUST_TLS
๐จ Breaking Changes and Migration Notes
1. XML Processing Changes
- Extension functions disabled by default - set
jdk.xml.enableExtensionFunctions=trueif needed - JAXP limits adjusted - may need to increase limits for large DTDs
2. HTTP Client Changes
- User-set Authorization headers now take precedence over Authenticator
- Enhanced header size limits with new defaults
3. Socket API Changes
connect()methods now close the Socket on failureAlreadyConnectedExceptionreplaced withIOExceptionfor connected SocketChannel sockets
4. Compiler Changes (javac)
- Stricter validation for local classes in static contexts
- Lambda method name generation updated
- Fixed EnclosingMethod attribute for local classes in lambdas
๐ Migration Checklist
Before Upgrading
- Review deprecated APIs in your codebase
- Test applications with extension functions disabled
- Check for usage of removed command-line options
- Validate TLS cipher suite configurations
- Test virtual thread synchronization performance
After Upgrading
- Enable compact object headers for memory savings (experimental)
- Update build scripts to handle new javac validations
- Consider migrating from ThreadLocal to ScopedValues
- Explore Stream Gatherers for custom stream operations
- Update monitoring tools for virtual thread diagnostics
๐ฎ Looking Ahead
Java 24 establishes a strong foundation for modern Java applications with:
- Enhanced performance through compact object headers and virtual thread improvements
- Future-ready security with quantum-resistant cryptographic algorithms
- Improved developer experience with streamlined language features
- Better tooling support for debugging and monitoring
The preview features in Java 24 provide a glimpse into the future direction of the platform, with pattern matching, structured concurrency, and scoped values becoming increasingly mature.
Java 24 Technical Keywords & Glossary
A quick reference guide to technical terms and concepts in Java 24, explained in simple one-line definitions.
๐ง JVM & Runtime Architecture
Compact Object Headers - Reduces Java object metadata from 96-128 bits to 64 bits, saving ~25% memory.
Virtual Threads - Lightweight JVM-managed threads that allow millions of concurrent tasks with minimal memory overhead.
Platform Threads - Traditional OS-managed threads that are expensive to create (1MB stack each) and limited by system resources.
Pinning (Virtual Threads) - When a virtual thread gets stuck to its carrier platform thread and canโt be shared with other virtual threads.
G1 Garbage Collector - Low-latency garbage collector designed for large heaps (>4GB) with predictable pause times.
Barrier Expansion - GC optimization technique that records memory access patterns to improve collection efficiency.
CDS (Class Data Sharing) - Shares pre-processed class metadata between JVM instances for faster startup and reduced memory usage.
AVX-512 - CPU instruction set that processes 512 bits of data simultaneously for high-performance computing.
๐ Cryptography & Security
Post-Quantum Cryptography - Encryption algorithms designed to resist attacks from quantum computers.
ML-KEM (Module-Lattice-Based Key Encapsulation) - Quantum-resistant method for securely sharing encryption keys over insecure networks.
ML-DSA (Module-Lattice-Based Digital Signatures) - Quantum-resistant digital signature algorithm for authentication and tamper detection.
FIPS 203/204 - Federal standards that define quantum-resistant cryptographic algorithms ML-KEM and ML-DSA.
Key Encapsulation Mechanism (KEM) - Cryptographic technique for securely establishing shared secret keys between parties.
PBKDF2 - Password-based key derivation that strengthens passwords by applying hash functions thousands of times.
HSS/LMS - Hash-based signature schemes that provide quantum-resistant digital signatures using one-time signatures.
๐ฏ Language Features & APIs
Pattern Matching - Language feature that combines type checking and variable extraction in a single operation.
instanceof with Patterns - Enhanced instanceof that tests types and extracts variables simultaneously without casting.
Scoped Values - Thread-safe way to share immutable data across method calls, designed to replace ThreadLocal.
Structured Concurrency - Programming model that treats related concurrent tasks as a single unit with automatic cleanup and error handling.
SIMD (Single Instruction, Multiple Data) - CPU capability to perform the same operation on multiple data elements simultaneously.
Vector API - Java API that compiles to SIMD instructions for high-performance mathematical computations.
Stream Gatherers - Custom intermediate operations for Java Streams that fill gaps between existing map/filter/reduce operations.
๐ Development Process Terms
JEP (JDK Enhancement Proposal) - Formal process for proposing, discussing, and tracking significant changes to the JDK.
Preview Feature - Complete, fully-specified feature available for developer feedback before becoming standard (requires โenable-preview).
Incubator Module - Experimental API with module name starting with jdk.incubator.* that may change significantly or be removed.
CSR (Compatibility & Specification Review) - Process ensuring proposed changes donโt break existing code compatibility.
forRemoval=true/false - Deprecation annotation indicating whether an API will be removed in the next major release.
๐ Networking & Protocols
HPack - HTTP/2 header compression algorithm that reduces bandwidth by referencing common headers instead of repeating them.
ALPN (Application-Layer Protocol Negotiation) - TLS extension that allows client and server to negotiate which application protocol to use.
TLS 1.3 Resumption Tickets - Server-issued tokens that clients use to resume previous TLS sessions without full handshake.
HTTP/2 Flow Control - Mechanism to prevent fast senders from overwhelming slow receivers in HTTP/2 multiplexed connections.
๐ฌ Advanced Concepts
Dynamic Table (HPack) - Cache of recently used HTTP headers that allows compression by referencing entries instead of full text.
Carrier Thread - Platform thread that executes virtual threads; virtual threads can be moved between different carrier threads.
Lattice-Based Cryptography - Mathematical foundation for quantum-resistant algorithms based on problems in high-dimensional lattices.
Class File Verifier - JVM component that validates bytecode for security and correctness before class loading.
Unified Logging - JVM logging framework that provides consistent log output format across different subsystems.
๐ ๏ธ Tools & Configuration
WiX Toolset - Windows installer creation tool that jpackage uses to build MSI installers.
jstatd - RMI server that provides remote monitoring interface for jstat performance counters (deprecated in Java 24).
jrunscript - Command-line tool for executing JavaScript and other scripting languages (deprecated in Java 24).
Module Path - Location where jlink looks for modules when creating custom runtime images.
Security Properties File - Configuration file that controls Java security settings and can now include other property files.
๐ Performance & Monitoring
MaxDirectMemorySize - JVM option that controls maximum memory for direct buffers (excludes internal temporary buffers in Java 24).
VirtualThreadSchedulerMXBean - JMX interface for monitoring virtual thread scheduler performance and configuration.
Message Digest Intrinsics - JVM optimizations that use CPU-specific instructions to accelerate cryptographic hash functions.
Bootstrap Class Path - JVM classpath containing core Java classes that are loaded before application classes.
๐ง System Integration
GTK (GIMP Toolkit) - Linux graphics library used by Swingโs GTK Look and Feel (GTK 2 support removed in Java 24).
PKCS #11 - Standard interface for hardware security modules and cryptographic tokens.
IANA Time Zone Database - Authoritative source for time zone information used by Javaโs date/time APIs.
CLDR (Common Locale Data Repository) - Unicode project providing locale data for internationalization.
โก Quick Reference
Experimental Features - New functionality enabled with -XX:+UnlockExperimentalVMOptions that may change or be removed.
Thread Dump - Snapshot of all threads and their current state, useful for debugging concurrency issues.
Heap Dump - Memory snapshot containing all objects in the JVM heap at a specific point in time.
Class Loading - Process of reading .class files and converting bytecode into runtime classes.
Bytecode Verification - Security check that validates .class files comply with JVM specification before execution.
๐ Additional Resources
- Java 24 Release Notes
- JDK Enhancement Proposals (JEPs)
- Java SE 24 API Documentation
- Migration Guide from Java 21 to 24
Last updated: March 2025 | Java 24 (Build 24+36)
Kambrathi
Published on January 16, 2024