All posts

Upgrading from Java 11 to Java 21: A Guide for AEM Developers

Daniel Strmečki

As an AEM developer, staying current with Java versions ensures we can leverage the latest features, security patches, and performance improvements. With Java 21 being the latest Long-Term Support (LTS) release, it's a critical upgrade for enterprises and developers working on Adobe Experience Manager (AEM) projects. Java LTS versions are supported for a longer period than non-LTS releases, making them ideal for production environments where stability and security are paramount. For example, Java 21 was released in September 2023 and will receive Premier Support until September 2028 and Extended Support until September 2031.

In the latest release of Cloud Manager 2025.1.0, Adobe announced that they now support Java 21 in AEMaaCS. Java 21 will be enabled for all customers in February 2025, along with the rollout of a new SonarQube version. This article focuses on API features and enhancements introduced between Java 11 and Java 21 that are most relevant for developers. We'll briefly touch on the upgrade progress and then dive into new APIs and syntax improvements with practical examples. The main goal of the article is to inform developers of the latest API improvements, so we can start using them immediately after the upgrade.

Upgrade Process

Cloud Manager defaults to Oracle JDK 8 for builds, but AEM Cloud Service customers should set the Maven JDK to 21 (preferred), 17, or 11. To set the Maven JDK to version 21 in Cloud Manager, add a .cloudmanager/java-version file to the pipeline’s Git branch with 21 as its content. Note that in order to migrate to Java 21, we must first upgrade to the latest SonarQube version.

The following adjustments are required to allow building and running AEM projects with Java 21:

  • Update the Java version to 21 in the maven-enforcer-plugin and maven-compiler-plugin
  • Update the usage of bnd-maven-plugin to version 6.4.0
  • Update the usage of aemanalyser-maven-plugin to version 1.6.6 or higher
  • Update the usage of maven-bundle-plugin to version 5.1.5 or higher
  • The maven-scr-plugin isn't directly compatible with Java 21, but updating the ASM dependency in the plugin configuration allows descriptor generation
  • Update the usage of the Java package org.objectweb.asm, often bundled in org.ow2.asm.* artifacts, to version 9.5 or higher
  • Update the usage of the Java packages org.apache.groovy or org.codehaus.groovy to version 4.0.22 or higher

AEM developers can download Java 21 SDK from Adobe's Software Distribution portal and install it on their machines. Then use it to build and deploy an AEM project locally to validate its functionality. Adobe recommends checking the logs for errors, which could indicate problems with classloading or bytecode weaving. Note that when running AEM locally with Java 21, the start scripts (crx-quickstart/bin/start) might fail due to the MaxPermSize param. To fix this, remove -XX:MaxPermSize=256M from the script or set the CQ_JVM_OPTS environment variable to -Xmx1024m -Djava.awt.headless=true.

For more detailed and up-to-date instructions, refer to the official Adobe documentation. Now, let's take a look at the new API features and syntax improvements that we can use after upgrading our AEM project to build and run with Java 21.

Pattern Matching

In Java 11, we had to manually cast an object to a type, even if we had done a type check before.

if (obj instanceof String) {
    String str = (String) obj;
    System.out.println(str.toUpperCase());
}

With the pattern matching feature introduced in Java 16, we can reduce boilerplate code by combining type checks and casts in a single operation.

if (obj instanceof String str) {
    System.out.println(str.toUpperCase());
}

Switch Expressions

In Java 11 switch statements, we had to manually add breaks to prevent the fall-through behavior, where execution continues into the next case if it is not explicitly stopped.

String result;

switch (day) {
    case MONDAY:
    case FRIDAY:
        result = "Workday";
        break;
    default:
        result = "Weekend";
}

Switch expressions were improved in Java 14 to simplify logic, improve readability, and reduce errors. The fall-through behavior is eliminated by using an arrow-like symbol that doesn’t require breaks.

String result = switch (day) {
    case MONDAY, FRIDAY -> "Workday";
    default -> "Weekend";
};

Text Blocks

Writing multiline texts in Java 11 was a real pain, as we had to concatenate multiple strings and manually add new lines.

String html = "<html>\n" +
              "    <head>\n" +
              "        <title>Welcome Page</title>\n" +
              "    </head>\n" +
              "    <body>\n" +
              "        <h1>Hello, World!</h1>\n" +
              "        <p>This is an example of HTML in Java.</p>\n" +
              "    </body>\n" +
              "</html>";

Text blocks were introduced in Java 13 to make working with multi-line strings, such as SQL queries or HTML templates, much cleaner. A text block is a multi-line string enclosed in triple double quotes ("""), which preserves line breaks and indentation and allows easier structured text handling.

String html = """
                  <html>
                      <head>
                          <title>Welcome Page</title>
                      </head>
                      <body>
                          <h1>Hello, World!</h1>
                          <p>This is an example of HTML in Java.</p>
                      </body>
                  </html>
                  """;

Records

In Java 11, we had to rely on third-party plugins like Lombok to avoid boilerplate code when creating simple DTOs. As an example, Lombok's Data annotation generates a no-args constructor, getter, and setter methods, toString(), equals(), and hashCode().

import lombok.Data;

@Data
public class User {
    private String name;
    private int age;
}

Records were introduced in Java 14 to provide a standard, compact syntax for immutable data objects. A record is a data structure for DTOs that automatically generates: a constructor, getter methods, toString(), equals(), and hashCode().

public record User(String name, int age) {}

Sealed Classes

The term sealed classes was introduced in Java version 15. A sealed class explicitly lists which subclasses can extend it using the permits keyword. Sealed classes restrict inheritance, helping developers define more predictable and safe class hierarchies.

public sealed class Shape permits Circle, Rectangle, CustomShape {}

public final class Circle extends Shape {}  // No further extension
public sealed class Rectangle extends Shape permits Square {}  // Can be extended only by Square
public non-sealed class CustomShape extends Shape {}  // Can be extended freely

Virtual Threads

Virtual Threads, introduced in Java 19, enable easier scaling for concurrent applications. Unlike traditional (platform) threads, virtual threads are lightweight and managed by the JVM rather than the operating system. Developers can create millions of threads with minimal performance overhead, making Java applications highly concurrent without complex asynchronous code.

Virtual threads use the same java.lang.Thread API, so existing code can be easily adopted. Creating and starting a virtual thread requires just one line of code.

Thread.startVirtualThread(() -> System.out.println("Hello from Virtual Thread"));

Developers can also use the Executors API to manage tasks in a thread pool-like structure.

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 10).forEach(i ->
        executor.submit(() -> System.out.println(Thread.currentThread()))
    );
}

Scoped Values

Scoped values are introduced as a preview feature in Java 21, to improve context propagation in multi-threaded environments. They are designed to improve data sharing across threads, especially in concurrent or asynchronous applications.

Unlike ThreadLocal, Scoped Values are designed to work safely with virtual threads without memory leaks and performance issues. Note that once a Scoped Value is bound to a scope, it cannot be modified within that scope.

private static final ScopedValue<String> USERNAME = ScopedValue.newInstance();

public static void main(String[] args) {
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        executor.submit(() -> ScopedValue.runWhere(USERNAME, "Daniel", () -> {
            processRequest();
        }));
        executor.submit(() -> ScopedValue.runWhere(USERNAME, "Ema", () -> {
            processRequest();
        }));
    }
}

private static void processRequest() {
    System.out.println("Processing request for user: " + USERNAME.get());
}

Structured Concurrency

Structured Concurrency is a concurrency model introduced as a preview feature in Java 21, aiming to make multi-threaded code more reliable, readable, and easier to manage. It helps developers structure concurrent tasks in the same way they structure code blocks, following a hierarchical and predictable flow.

In Java 11, we had to rely on the traditional concurrency models, like manually managing threads or using ExecutorService which could lead to complex code, resource leaks, and difficult error handling.

public static void main(String[] args) throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(2);
    Future<String> task1 = executor.submit(() -> fetchData("Task 1", 2));
    Future<String> task2 = executor.submit(() -> fetchData("Task 2", 3));

    // No task failure handling, complex exception handling
    System.out.println(task1.get());
    System.out.println(task2.get());
    executor.shutdown();
}

By using Structured Concurrency in Java 21, the try-with-resources block ensures all threads are cleaned up, even if exceptions occur. We can easily cancel all tasks if just one of the tasks fails and throw an exception.

 public static void main(String[] args) throws Exception {
    try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
        var task1 = scope.fork(() -> fetchData("Task 1", 2)); // Forking within the scope
        var task2 = scope.fork(() -> fetchData("Task 2", 3));

        scope.join();  // Wait until both tasks are done or one fails
        scope.throwIfFailed(); // Propagates exceptions if any

        System.out.println(task1.resultNow()); // Collect results
        System.out.println(task2.resultNow());
    }
}

Collections and Streams

Java has supported immutable collections since Java 9, but Java 21 continues to enhance these features with better performance and cleaner APIs. Immutable collections created with List.of() and Map.of() are now faster and use less memory.

Map<String, String> config = Map.of("key1", "value1", "key2", "value2");

Java 21 also introduces the SequencedCollection, SequencedSet, and SequencedMap interfaces, providing more predictable element ordering.

public static void main(String[] args) {
    SequencedCollection<String> list = List.of("A", "B", "C");
    System.out.println(list.getFirst());  // A
    System.out.println(list.getLast());   // C
    System.out.println(list.reversed());  // [C, B, A]
}

The toList() collector added in Java 16 simplifies collecting stream results into an immutable list.

List<String> titles = assets.stream()
    .map(Asset::getTitle)
    .toList();

Security and Performance

Let's mention some of the many security enhancements available in Java 21, compared to Java 11:

  • Strong encapsulation in the Java Module System prevents unintended access to internal APIs.
  • Class-loader isolation reduces the risk of classpath injection attacks.
  • Defaults to stronger encryption algorithms like SHA-256 and AES-GCM.
  • TLS 1.3 is enabled by default for secure communications.
  • Improvements for FIPS compliance, making it easier to meet regulatory standards in secure environments.
  • PKCS#11 Updates for better hardware security module (HSM) support.
  • Improved KeyStore API for managing keys and certificates securely.
  • Security policies are now stricter by default.

Finally, let's mention some of the many performance enhancements available in Java 21, compared to Java 11:

  • Virtual threads deserve another mention here, as they bring a massive improvement to Java concurrency.
  • Optimized String operations reduce the memory footprint for text-heavy applications.
  • Foreign Function and Memory API replaces JNI for better performance when interacting with native libraries.
  • Improved Just-In-Time (JIT) compiler for faster code execution.
  • G1 GC & ZGC garbage collection is improved for lower latency and better throughput.

Conclusion

Upgrading to Java 21 unlocks some cool new features for AEM developers, from modern syntax improvements to new APIs. There is absolutely no reason for any teams or projects not to upgrade to Java 21 as soon as possible. It makes perfect sense to be up-to-date with the core programming language used in a platform like AEM. Besides, even if you are not blown away by the new APIs for developers, then security and performance benefits still justify the upgrade effort.

As Java is backward compatible, the upgrade process should be smooth, requiring only a few code changes. That means developers can upgrade to Java 21 and keep using the same code written for Java 11. Then, we can gradually introduce the newly available syntax and APIs. If your AEM codebase is well covered by meaningful unit and/or integration tests, then you can be very confident that the upgrade will be smooth and successful.

All posts

Blog

All posts

If these challenges sound familiar, explore how we help enterprises reduce risk.