DEV Community

code performance
code performance

Posted on

Java Development Kit 24 - Comprehensive API Documentation

Table of Contents

  1. Overview
  2. Major New Features in JDK 24
  3. Language Features
  4. Core Java APIs
  5. Collections Framework
  6. Networking APIs
  7. Security Libraries
  8. Concurrency and Threading
  9. I/O and NIO APIs
  10. Time and Date APIs
  11. Reflection and Introspection
  12. Tools and Utilities

Overview

Java Development Kit (JDK) 24 is an implementation of the Java SE 24 Platform, released in March 2025. This documentation covers all public APIs, methods, functions, and components available in JDK 24.

Version Information:

  • Release Date: March 18, 2025
  • Version String: 24+36
  • Unicode Support: Unicode 16.0
  • Time Zone Data: IANA 2024b

Major New Features in JDK 24

1. Language Preview Features

Primitive Types in Patterns, instanceof, and switch (Second Preview)

Pattern matching enhanced to support primitive types in all pattern contexts.

// Example: Pattern matching with primitives
public String checkNumber(Object obj) {
    return switch (obj) {
        case int i when i > 0 -> "Positive integer: " + i;
        case int i when i < 0 -> "Negative integer: " + i;
        case int i -> "Zero";
        case double d -> "Double: " + d;
        case null -> "Null value";
        default -> "Other type";
    };
}
Enter fullscreen mode Exit fullscreen mode

Flexible Constructor Bodies (Third Preview)

Allows statements before explicit constructor invocation.

public class Example {
    private final String data;

    public Example(String input) {
        // Statements before super() call
        if (input == null) {
            throw new IllegalArgumentException("Input cannot be null");
        }
        this.data = input.trim().toLowerCase();
        super(); // or this()
    }
}
Enter fullscreen mode Exit fullscreen mode

Module Import Declarations (Second Preview)

Simplifies importing all packages from a module.

import module java.base;
import module java.logging;

// Now all exported packages from these modules are available
Enter fullscreen mode Exit fullscreen mode

Simple Source Files and Instance Main Methods (Fourth Preview)

Simplified entry points for beginner programs.

// Simple source file without class declaration
void main() {
    println("Hello, World!");
}
Enter fullscreen mode Exit fullscreen mode

2. Performance and Runtime Improvements

Compact Object Headers (Experimental)

Reduces object header size from 96-128 bits to 64 bits on 64-bit architectures.

# Enable compact object headers
java -XX:+UnlockExperimentalVMOptions -XX:+UseCompactObjectHeaders MyApp
Enter fullscreen mode Exit fullscreen mode

Synchronize Virtual Threads without Pinning

Virtual threads no longer pin platform threads when using synchronized blocks.

Ahead-of-Time Class Loading & Linking

Improves startup time by caching loaded and linked class forms.

3. Library Enhancements

Stream Gatherers

Custom intermediate operations for streams.

// Using built-in gatherers
List<String> result = Stream.of("a", "b", "c", "d")
    .gather(Gatherers.windowFixed(2))
    .map(window -> String.join("-", window))
    .toList(); // ["a-b", "c-d"]
Enter fullscreen mode Exit fullscreen mode

Class-File API

Standard API for parsing, generating, and transforming Java class files.

import java.lang.classfile.*;

// Reading a class file
ClassFile classFile = ClassFile.of();
ClassModel model = classFile.parse(classBytes);

// Transforming a class
byte[] newClassBytes = classFile.transform(model,
    ClassTransform.transformingMethods(
        MethodTransform.transformingCode(/* transformation logic */)
    ));
Enter fullscreen mode Exit fullscreen mode

Language Features

JEP 488: Primitive Types in Patterns

Enhanced pattern matching supporting all primitive types.

Key APIs:

  • Enhanced instanceof operator
  • Extended switch expressions and statements
  • Pattern matching in all contexts

Examples:

// instanceof with primitives
public boolean isEven(Object obj) {
    return obj instanceof int i && i % 2 == 0;
}

// switch with primitive patterns
public String describe(Object value) {
    return switch (value) {
        case byte b -> "Byte: " + b;
        case short s -> "Short: " + s;
        case int i -> "Integer: " + i;
        case long l -> "Long: " + l;
        case float f -> "Float: " + f;
        case double d -> "Double: " + d;
        case char c -> "Character: " + c;
        case boolean b -> "Boolean: " + b;
        default -> "Other: " + value;
    };
}
Enter fullscreen mode Exit fullscreen mode

Core Java APIs

java.lang Package

java.lang.Object

Base class for all Java objects.

public class Object {
    public native int hashCode();
    public boolean equals(Object obj);
    public String toString();
    public final Class<?> getClass();
    protected Object clone() throws CloneNotSupportedException;
    public final void notify();
    public final void notifyAll();
    public final void wait() throws InterruptedException;
    // Additional wait() overloads
    protected void finalize() throws Throwable; // Deprecated
}
Enter fullscreen mode Exit fullscreen mode

java.lang.String

Immutable character sequences with enhanced functionality.

New in JDK 24:

// Enhanced string methods
String text = "Hello World";

// indexOf with range
int index = text.indexOf('o', 2, 8); // Search between indices 2-8

// splitWithDelimiters - includes delimiters in result
String[] parts = text.splitWithDelimiters("\\s", 0);
Enter fullscreen mode Exit fullscreen mode

java.lang.Class

Runtime representation of classes and interfaces.

Enhanced in JDK 24:

Class<?> clazz = String.class;

// Access flags (new in JDK 20, enhanced in 24)
Set<AccessFlag> flags = clazz.accessFlags();

// Check for specific features
boolean isRecord = clazz.isRecord();
boolean isSealed = clazz.isSealed();
boolean isHidden = clazz.isHidden();

// Get permitted subclasses (sealed classes)
Class<?>[] permitted = clazz.getPermittedSubclasses();

// Get record components
RecordComponent[] components = clazz.getRecordComponents();
Enter fullscreen mode Exit fullscreen mode

java.lang.Process

Process execution and management.

New in JDK 24:

ProcessBuilder pb = new ProcessBuilder("ls", "-la");
Process process = pb.start();

// New Duration-based wait method
Duration timeout = Duration.ofSeconds(30);
boolean finished = process.waitFor(timeout);

// Enhanced I/O handling
BufferedReader reader = process.inputReader();
BufferedWriter writer = process.outputWriter();
BufferedReader errorReader = process.errorReader();
Enter fullscreen mode Exit fullscreen mode

java.util Package

java.util.List, Set, Map

Enhanced collection interfaces.

// Sequenced collections (JDK 21+, stable in JDK 24)
List<String> list = new ArrayList<>();
list.addFirst("first");
list.addLast("last");
String first = list.getFirst();
String last = list.getLast();

// Reversed views
List<String> reversed = list.reversed();
Enter fullscreen mode Exit fullscreen mode

java.util.HexFormat

Hexadecimal formatting utilities.

HexFormat hex = HexFormat.of();

// Convert bytes to hex
byte[] bytes = {10, 20, 30};
String hexString = hex.formatHex(bytes); // "0a141e"

// Parse hex back to bytes
byte[] parsed = hex.parseHex(hexString);

// With delimiters
HexFormat delimited = HexFormat.ofDelimiter(":");
String formatted = delimited.formatHex(bytes); // "0a:14:1e"
Enter fullscreen mode Exit fullscreen mode

Collections Framework

Stream API Enhancements

Stream Gatherers (JEP 485)

Custom intermediate operations for enhanced stream processing.

import java.util.stream.Gatherer;
import java.util.stream.Gatherers;

// Built-in gatherers
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);

// Window operations
List<List<Integer>> windows = numbers.stream()
    .gather(Gatherers.windowFixed(3))
    .toList(); // [[1,2,3], [4,5,6]]

// Sliding windows
List<List<Integer>> sliding = numbers.stream()
    .gather(Gatherers.windowSliding(3))
    .toList(); // [[1,2,3], [2,3,4], [3,4,5], [4,5,6]]

// Fold operations
String concatenated = Stream.of("a", "b", "c")
    .gather(Gatherers.fold("", String::concat))
    .findFirst()
    .orElse("");

// Custom gatherer
Gatherer<String, ?, String> upperCaseGatherer = 
    Gatherer.of(
        StringBuilder::new,                    // Initial state
        (sb, element, downstream) -> {         // Integration function
            sb.append(element.toUpperCase());
            if (sb.length() >= 3) {
                downstream.push(sb.toString());
                sb.setLength(0);
            }
            return true;
        },
        (sb, downstream) -> {                  // Finish function
            if (sb.length() > 0) {
                downstream.push(sb.toString());
            }
        }
    );
Enter fullscreen mode Exit fullscreen mode

Enhanced Collection Operations

// Pattern matching in collections
List<Object> mixed = List.of(1, "hello", 2.5, 3);

List<Integer> integers = mixed.stream()
    .filter(obj -> obj instanceof Integer)
    .map(obj -> (Integer) obj)
    .toList();

// With pattern matching (preview)
List<Integer> integersPattern = mixed.stream()
    .mapMulti((obj, consumer) -> {
        if (obj instanceof Integer i) {
            consumer.accept(i);
        }
    })
    .toList();
Enter fullscreen mode Exit fullscreen mode

Networking APIs

HTTP Client Enhancements

java.net.http.HttpClient

Modern HTTP client with HTTP/2 support.

import java.net.http.*;
import java.net.http.HttpResponse.BodyHandlers;

HttpClient client = HttpClient.newBuilder()
    .version(HttpClient.Version.HTTP_2)
    .connectTimeout(Duration.ofSeconds(20))
    .build();

// Basic GET request
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/data"))
    .timeout(Duration.ofMinutes(2))
    .header("Content-Type", "application/json")
    .GET()
    .build();

// Synchronous response
HttpResponse<String> response = client.send(request, 
    BodyHandlers.ofString());

System.out.println(response.statusCode());
System.out.println(response.body());

// Asynchronous response
CompletableFuture<HttpResponse<String>> asyncResponse = 
    client.sendAsync(request, BodyHandlers.ofString());

asyncResponse.thenAccept(resp -> {
    System.out.println("Status: " + resp.statusCode());
    System.out.println("Body: " + resp.body());
});
Enter fullscreen mode Exit fullscreen mode

Enhanced Socket Operations

// Socket with improved connection handling
Socket socket = new Socket();
socket.connect(new InetSocketAddress("example.com", 80), 
    Duration.ofSeconds(10)); // Duration-based timeout

// Unix Domain Sockets
UnixDomainSocketAddress address = 
    UnixDomainSocketAddress.of("/tmp/socket");
SocketChannel channel = SocketChannel.open(StandardProtocolFamily.UNIX);
channel.connect(address);
Enter fullscreen mode Exit fullscreen mode

New HTTP Limits and Security

JDK 24 introduces default limits for HTTP implementations:

// System properties for HTTP limits
System.setProperty("jdk.http.maxHeaderSize", "512000"); // 500KB
System.setProperty("jdk.httpclient.maxNonFinalResponses", "10");
System.setProperty("jdk.httpclient.maxLiteralWithIndexing", "1024");
Enter fullscreen mode Exit fullscreen mode

Security Libraries

Quantum-Resistant Cryptography

ML-KEM (Module-Lattice-Based Key Encapsulation Mechanism)

Post-quantum cryptographic algorithm for secure key exchange.

import javax.crypto.KEM;
import javax.crypto.KEM.Encapsulator;
import javax.crypto.KEM.Decapsulator;

// Generate ML-KEM key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ML-KEM");
keyGen.initialize(512); // 512, 768, or 1024 bit security levels
KeyPair keyPair = keyGen.generateKeyPair();

// Sender side - encapsulation
KEM kem = KEM.getInstance("ML-KEM");
Encapsulator encapsulator = kem.newEncapsulator(keyPair.getPublic());
KEM.Encapsulated encapsulated = encapsulator.encapsulate();

byte[] sharedSecret = encapsulated.key().getEncoded();
byte[] encapsulation = encapsulated.encapsulation();

// Receiver side - decapsulation
Decapsulator decapsulator = kem.newDecapsulator(keyPair.getPrivate());
SecretKey recoveredSecret = decapsulator.decapsulate(encapsulation);
Enter fullscreen mode Exit fullscreen mode

ML-DSA (Module-Lattice-Based Digital Signature Algorithm)

Post-quantum digital signatures.

// Generate ML-DSA key pair
KeyPairGenerator sigKeyGen = KeyPairGenerator.getInstance("ML-DSA");
sigKeyGen.initialize(2); // Security levels 2, 3, or 5
KeyPair sigKeyPair = sigKeyGen.generateKeyPair();

// Sign data
Signature signature = Signature.getInstance("ML-DSA");
signature.initSign(sigKeyPair.getPrivate());
signature.update("Hello, quantum-safe world!".getBytes());
byte[] signatureBytes = signature.sign();

// Verify signature
signature.initVerify(sigKeyPair.getPublic());
signature.update("Hello, quantum-safe world!".getBytes());
boolean verified = signature.verify(signatureBytes);
Enter fullscreen mode Exit fullscreen mode

Key Derivation Function API (Preview)

import javax.crypto.KDF;
import javax.crypto.spec.KDFParameterSpec;

// PBKDF2 key derivation
KDF kdf = KDF.getInstance("PBKDF2WithHmacSHA256");
KDFParameterSpec params = KDFParameterSpec.ofPBKDF2()
    .password("password".toCharArray())
    .salt("salt".getBytes())
    .iterations(10000)
    .keyLength(256)
    .build();

SecretKey derivedKey = kdf.deriveKey("AES", params);
Enter fullscreen mode Exit fullscreen mode

Enhanced TLS Security

// TLS configuration with new cipher suite controls
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);

SSLSocketFactory factory = context.getSocketFactory();
SSLSocket socket = (SSLSocket) factory.createSocket("example.com", 443);

// Pattern-based cipher suite disabling is now supported
// via jdk.tls.disabledAlgorithms security property
Enter fullscreen mode Exit fullscreen mode

Concurrency and Threading

Virtual Threads Enhancements

Synchronization without Pinning (JEP 491)

Virtual threads no longer pin carrier threads when using synchronized blocks.

// Virtual threads with synchronized blocks
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    List<Future<String>> futures = new ArrayList<>();

    for (int i = 0; i < 1000; i++) {
        int taskId = i;
        Future<String> future = executor.submit(() -> {
            synchronized (this) {  // No longer pins carrier thread
                Thread.sleep(Duration.ofSeconds(1));
                return "Task " + taskId + " completed";
            }
        });
        futures.add(future);
    }

    // Collect results
    for (Future<String> future : futures) {
        System.out.println(future.get());
    }
}
Enter fullscreen mode Exit fullscreen mode

Virtual Thread Scheduler Monitoring

// New JMX interface for virtual thread monitoring
import jdk.management.VirtualThreadSchedulerMXBean;
import java.lang.management.ManagementFactory;

VirtualThreadSchedulerMXBean scheduler = ManagementFactory
    .getPlatformMXBean(VirtualThreadSchedulerMXBean.class);

// Monitor scheduler metrics
int parallelism = scheduler.getParallelism();
long poolSize = scheduler.getPoolSize();
long queuedTaskCount = scheduler.getQueuedTaskCount();

// Dynamically adjust parallelism
scheduler.setParallelism(Runtime.getRuntime().availableProcessors());
Enter fullscreen mode Exit fullscreen mode

Structured Concurrency (Fourth Preview)

import java.util.concurrent.StructuredTaskScope;

// Coordinated task execution
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
    // Submit related tasks
    Future<String> user = scope.fork(() -> fetchUser(userId));
    Future<String> orders = scope.fork(() -> fetchOrders(userId));
    Future<String> preferences = scope.fork(() -> fetchPreferences(userId));

    // Wait for all tasks or fail fast
    scope.join();           // Wait for all tasks
    scope.throwIfFailed();  // Throw if any failed

    // All tasks completed successfully
    return new UserProfile(user.resultNow(), 
                          orders.resultNow(), 
                          preferences.resultNow());
}
Enter fullscreen mode Exit fullscreen mode

Scoped Values (Fourth Preview)

import java.lang.ScopedValue;

// Thread-local-like data sharing without inheritance issues
private static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
private static final ScopedValue<User> CURRENT_USER = ScopedValue.newInstance();

public void handleRequest(String requestId, User user) {
    ScopedValue.where(REQUEST_ID, requestId)
               .where(CURRENT_USER, user)
               .run(() -> {
                   // All child operations can access these values
                   processRequest();
               });
}

private void processRequest() {
    String requestId = REQUEST_ID.get();
    User user = CURRENT_USER.get();
    // Use values throughout the call stack
}
Enter fullscreen mode Exit fullscreen mode

I/O and NIO APIs

Enhanced File Operations

java.nio.file.Files

File system operations with new utilities.

import java.nio.file.*;

// Enhanced file operations
Path source = Paths.get("source.txt");
Path target = Paths.get("target.txt");

// Copy with options
Files.copy(source, target, 
    StandardCopyOption.REPLACE_EXISTING,
    StandardCopyOption.COPY_ATTRIBUTES,
    LinkOption.NOFOLLOW_LINKS);

// Watch service for file system events
WatchService watchService = FileSystems.getDefault().newWatchService();
Path directory = Paths.get("/tmp");
directory.register(watchService, 
    StandardWatchEventKinds.ENTRY_CREATE,
    StandardWatchEventKinds.ENTRY_DELETE,
    StandardWatchEventKinds.ENTRY_MODIFY);

// Process file system events
while (true) {
    WatchKey key = watchService.take();
    for (WatchEvent<?> event : key.pollEvents()) {
        System.out.println("Event: " + event.kind() + 
                          " File: " + event.context());
    }
    key.reset();
}
Enter fullscreen mode Exit fullscreen mode

Memory-Mapped Files

// Memory-mapped file operations
try (RandomAccessFile file = new RandomAccessFile("large-file.dat", "rw");
     FileChannel channel = file.getChannel()) {

    // Map file to memory
    MappedByteBuffer buffer = channel.map(
        FileChannel.MapMode.READ_WRITE, 0, file.length());

    // Direct memory access
    buffer.putInt(0, 42);
    int value = buffer.getInt(0);

    // Force changes to disk
    buffer.force();
}
Enter fullscreen mode Exit fullscreen mode

Enhanced Character Stream Operations

java.io.Reader Enhancements

// New Reader.of(CharSequence) method
CharSequence content = "Hello, World!";
Reader reader = Reader.of(content);

char[] buffer = new char[5];
int bytesRead = reader.read(buffer);
System.out.println(new String(buffer, 0, bytesRead)); // "Hello"
Enter fullscreen mode Exit fullscreen mode

Time and Date APIs

java.time Package

Comprehensive date and time handling based on ISO-8601.

Enhanced Time Zone Support

import java.time.*;
import java.time.zone.*;

// Time zone database 2024b support
ZoneId zone = ZoneId.of("America/New_York");
ZonedDateTime now = ZonedDateTime.now(zone);

// Get available zones
Set<String> zones = ZoneId.getAvailableZoneIds();

// Time zone transitions
ZoneRules rules = zone.getRules();
ZoneOffsetTransition transition = rules.nextTransition(Instant.now());
Enter fullscreen mode Exit fullscreen mode

Duration and Period Calculations

// Enhanced duration support
LocalDateTime start = LocalDateTime.of(2024, 1, 1, 10, 0);
LocalDateTime end = LocalDateTime.of(2024, 1, 1, 15, 30);

Duration duration = Duration.between(start, end);
long hours = duration.toHours();
long minutes = duration.toMinutesPart();

// Period for date-based amounts
LocalDate birthDate = LocalDate.of(1990, 5, 15);
LocalDate today = LocalDate.now();
Period age = Period.between(birthDate, today);

System.out.println("Age: " + age.getYears() + " years, " + 
                   age.getMonths() + " months");
Enter fullscreen mode Exit fullscreen mode

Instant and Clock

// High-precision time measurement
Instant start = Instant.now();
// ... some operation
Instant end = Instant.now();
Duration elapsed = Duration.between(start, end);

// Custom clock for testing
Clock fixedClock = Clock.fixed(
    Instant.parse("2024-01-01T00:00:00Z"), 
    ZoneOffset.UTC);

LocalDateTime fixedTime = LocalDateTime.now(fixedClock);
Enter fullscreen mode Exit fullscreen mode

Reflection and Introspection

Enhanced Reflection APIs

java.lang.reflect.AccessFlag

Runtime access to Java access modifiers.

import java.lang.reflect.*;

Class<?> clazz = String.class;

// Access flags for class
Set<AccessFlag> classFlags = clazz.accessFlags();
boolean isPublic = classFlags.contains(AccessFlag.PUBLIC);
boolean isFinal = classFlags.contains(AccessFlag.FINAL);

// Method access flags
Method method = clazz.getMethod("length");
Set<AccessFlag> methodFlags = method.accessFlags();
boolean isNative = methodFlags.contains(AccessFlag.NATIVE);

// Field access flags
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
    Set<AccessFlag> fieldFlags = field.accessFlags();
    System.out.println(field.getName() + ": " + fieldFlags);
}
Enter fullscreen mode Exit fullscreen mode

Record Component Access

// Working with record components
public record Person(String name, int age, String email) {}

Class<?> personClass = Person.class;
RecordComponent[] components = personClass.getRecordComponents();

for (RecordComponent component : components) {
    System.out.println("Component: " + component.getName());
    System.out.println("Type: " + component.getType());
    System.out.println("Accessor: " + component.getAccessor());

    // Access flags for record components
    Set<AccessFlag> flags = component.accessFlags();
}
Enter fullscreen mode Exit fullscreen mode

Method Handles

import java.lang.invoke.*;

// Method handle creation and invocation
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodType type = MethodType.methodType(int.class);
MethodHandle lengthHandle = lookup.findVirtual(String.class, "length", type);

String text = "Hello";
int length = (int) lengthHandle.invoke(text); // 5

// Static method handles
MethodType staticType = MethodType.methodType(String.class, Object.class);
MethodHandle toStringHandle = lookup.findStatic(String.class, "valueOf", staticType);
String result = (String) toStringHandle.invoke(42); // "42"
Enter fullscreen mode Exit fullscreen mode

Tools and Utilities

Class-File API (JEP 484)

import java.lang.classfile.*;
import java.lang.classfile.attribute.*;
import java.lang.classfile.constantpool.*;

// Parse a class file
ClassFile cf = ClassFile.of();
byte[] classBytes = Files.readAllBytes(Paths.get("MyClass.class"));
ClassModel model = cf.parse(classBytes);

// Inspect class structure
System.out.println("Class: " + model.thisClass().asInternalName());
System.out.println("Superclass: " + model.superclass().map(ClassEntry::asInternalName));

// Access methods
for (MethodModel method : model.methods()) {
    System.out.println("Method: " + method.methodName().stringValue());

    // Access method code
    method.findAttribute(Attributes.code()).ifPresent(codeAttr -> {
        CodeModel code = codeAttr;
        System.out.println("Max stack: " + code.maxStack());
        System.out.println("Max locals: " + code.maxLocals());
    });
}

// Transform class file
byte[] transformed = cf.transform(model, ClassTransform.transformingMethods(
    (methodBuilder, methodElement) -> {
        if (methodElement instanceof MethodModel mm && 
            mm.methodName().stringValue().equals("targetMethod")) {
            // Add logging to method
            methodBuilder.transformCode((codeBuilder, codeElement) -> {
                if (codeElement instanceof ReturnInstruction) {
                    // Add logging before return
                    codeBuilder.getstatic(ClassDesc.of("java.lang.System"), 
                                        "out", 
                                        ClassDesc.of("java.io.PrintStream"));
                    codeBuilder.ldc("Method returning");
                    codeBuilder.invokevirtual(ClassDesc.of("java.io.PrintStream"), 
                                            "println", 
                                            MethodTypeDesc.of(ClassDesc.of("void"), 
                                                             ClassDesc.of("java.lang.String")));
                }
                codeBuilder.with(codeElement);
            });
        } else {
            methodBuilder.with(methodElement);
        }
    }
));
Enter fullscreen mode Exit fullscreen mode

JAR Tool Enhancements

# New options in JDK 24
jar --extract --keep-old-files --file myapp.jar   # Don't overwrite existing files
jar --extract --dir /target/directory --file myapp.jar   # Extract to specific directory
jar --create --file myapp.jar --main-class com.example.Main *.class
Enter fullscreen mode Exit fullscreen mode

JFR (Java Flight Recorder) APIs

import jdk.jfr.*;

// Custom JFR events
@Name("com.example.ProcessingEvent")
@Label("Processing Event")
@Description("Tracks processing operations")
public class ProcessingEvent extends Event {
    @Label("Operation")
    String operation;

    @Label("Duration")
    @Timespan
    long duration;

    @Label("Success")
    boolean success;
}

// Usage
public void processData(String data) {
    ProcessingEvent event = new ProcessingEvent();
    event.operation = "data-processing";
    event.begin();

    try {
        // Processing logic
        Thread.sleep(100);
        event.success = true;
    } catch (Exception e) {
        event.success = false;
        throw e;
    } finally {
        event.end();
        event.commit();
    }
}
Enter fullscreen mode Exit fullscreen mode

JMX Enhancements

import javax.management.*;
import java.lang.management.*;

// Virtual thread scheduler monitoring
VirtualThreadSchedulerMXBean vtScheduler = 
    ManagementFactory.getPlatformMXBean(VirtualThreadSchedulerMXBean.class);

System.out.println("Pool size: " + vtScheduler.getPoolSize());
System.out.println("Queued tasks: " + vtScheduler.getQueuedTaskCount());

// Adjust parallelism dynamically
vtScheduler.setParallelism(8);
Enter fullscreen mode Exit fullscreen mode

Migration Notes from Previous Versions

Removed Features in JDK 24

  • Linux Desktop GTK2 support removed
  • JDK 1.1 compatible behavior for EST/MST/HST time zones
  • javax.naming.Context.APPLET constant removed
  • Security Manager permanently disabled
  • Various deprecated command-line options removed

Deprecated Features

  • java.util.zip.ZipError deprecated for removal
  • jstatd and jrunscript tools deprecated
  • jdk.jsobject module deprecated
  • Various legacy command-line options deprecated

Security Changes

  • TLS_RSA cipher suites disabled by default
  • Enhanced distrust policies for certain certificate authorities
  • JNDI remote code downloading permanently disabled

Performance Considerations

Memory Management

  • Compact Object Headers reduce memory usage by ~25% (experimental)
  • Internal temporary direct buffers no longer count against MaxDirectMemorySize
  • Enhanced garbage collection with ZGC generational mode as default

Startup Performance

  • Ahead-of-Time Class Loading & Linking significantly improves startup time
  • CDS (Class Data Sharing) archives available for compact object headers

Runtime Performance

  • Virtual threads synchronization improvements
  • Enhanced JIT compilation with late barrier expansion for G1
  • SHA3 performance improvements (6-27% faster)

Best Practices

Using New Language Features

  1. Pattern Matching: Use for cleaner, more readable code
  2. Virtual Threads: Prefer for I/O-bound tasks
  3. Structured Concurrency: Use for coordinated parallel operations
  4. Scoped Values: Replace ThreadLocal where appropriate

Security Best Practices

  1. Quantum-Ready Cryptography: Start migrating to ML-KEM and ML-DSA
  2. TLS Configuration: Use modern cipher suites
  3. Certificate Management: Update certificates from deprecated CAs

Performance Optimization

  1. Enable Compact Object Headers for memory-constrained applications
  2. Use Stream Gatherers for complex stream operations
  3. Leverage Virtual Threads for high-concurrency applications

Conclusion

JDK 24 represents a significant advancement in the Java platform, with major improvements in:

  • Language expressiveness through enhanced pattern matching
  • Runtime performance via compact object headers and virtual thread improvements
  • Security with quantum-resistant cryptography
  • Developer productivity through simplified APIs and better tooling

This documentation provides a comprehensive overview of the public APIs available in JDK 24. For detailed API references, consult the official Javadoc documentation at https://docs.oracle.com/en/java/javase/24/docs/api/.


Last updated: Based on JDK 24 GA release (March 2025) and JDK 24.0.1 update (April 2025)

Top comments (0)