Java 21 features for AI apps: records, sealed types and more

LLM code has three hard parts: messy JSON, replies that come in many shapes, and calls that take seconds. Modern Java has a feature for each. Here is how records, sealed types, pattern matching, text blocks and virtual threads fit AI work.

Four tilted cards. Records, requests and replies: record Message with role and content, and record Invoice with number and total; JSON in, typed data out. Sealed plus pattern matching, in yellow: a switch on reply with cases Answer, ToolCall and Failed; forget a case and it won't compile. Text blocks, prompts: a String prompt written as a text block, You are a support assistant, Ticket %s, formatted with the ticket. Virtual threads, waiting, on a dark card: 100 LLM calls of 1 second each take about 100 seconds one by one, and about 10 seconds 10 at a time; plain blocking code, cheap threads.
Fig. 1 — One feature for each hard part of LLM code.

In part 3 we called an LLM with plain Java. It worked, but real AI code soon runs into three problems:

  1. The data is messy. JSON goes out, JSON comes back, and sometimes the model’s answer is itself JSON that your app has to trust.
  2. Replies come in many shapes. A normal answer, a request to call a tool, an answer cut off by the length limit, an error. Miss one and you have a bug.
  3. Calls are slow. Each one can take seconds. A real app makes many of them at once.

Modern Java has a clean answer for each problem. This part of Java for AI Engineers shows five features, all in Java 21, which is a long-term support (LTS) release. Everything here also works on Java 25, the newest LTS.

We won’t explain each feature from scratch. Our Modern Java guides already do that, and each section links to the full one. Here we focus on how they fit AI work.

1. Records: the shape of your data

A record is a one-line class that just holds data. That is exactly what LLM code is full of: messages, requests, responses, usage counts.

record Message(String role, String content) {}
record ChatRequest(String model, List<Message> messages, double temperature) {}

In part 3, Jackson turned these records into JSON and back. No getters, no setters, no equals to write. Records are also immutable, so a message can’t be changed by accident after you add it to the history.

Validate settings in a compact constructor

A record can check its own values. If someone passes a temperature of 7, fail now, with a clear message, instead of getting a confusing 400 error from the API later:

record ChatOptions(String model, double temperature, int maxTokens) {
    ChatOptions {
        if (model == null || model.isBlank())
            throw new IllegalArgumentException("model is required");
        if (temperature < 0 || temperature > 2)
            throw new IllegalArgumentException("temperature must be between 0 and 2");
        if (maxTokens <= 0)
            throw new IllegalArgumentException("maxTokens must be positive");
    }
}

(The 0 to 2 range is OpenAI’s. Use the range your provider documents.)

Structured output: turn the answer into a Java object

This is where records really shine. Often you don’t want a paragraph from the model, you want data. Say an email arrives with an invoice in it. You ask the model to reply with JSON only, then read that JSON straight into a record:

@JsonIgnoreProperties(ignoreUnknown = true)
record Invoice(String number, String customer, double total, List<String> items) {
    Invoice {
        if (number == null || number.isBlank())
            throw new IllegalArgumentException("invoice number missing");
        if (total < 0)
            throw new IllegalArgumentException("total can't be negative");
        items = items == null ? List.of() : List.copyOf(items);
    }
}
String reply = llm.chat(List.of(new Message("user", prompt)));   // the client from part 3
Invoice invoice = JSON.readValue(reply, Invoice.class);

If the model returns {"number": "INV-2041", "customer": "Asha Traders", "total": 18500, "items": ["2 keyboards", "1 monitor"]}, you get a normal Java object:

Invoice[number=INV-2041, customer=Asha Traders, total=18500.0, items=[2 keyboards, 1 monitor]]

And if the model gets it wrong, say it leaves out the invoice number, Jackson throws an exception with “invoice number missing” inside it. The bad data never gets into your system. Remember from part 2: the model predicts what is likely, not what is true. The record is your gatekeeper.

2. Sealed types and pattern matching: handle every kind of reply

A call to an LLM can end in several different ways:

  • a normal answer,
  • a tool call, where the model asks your code to run something (like “look up order 1234”),
  • a cut-off answer, because it hit the length limit (finish_reason is "length"),
  • a failure, like a rate limit or a bad key.

With a sealed interface, you list every possibility in one place:

sealed interface LlmReply permits Answer, ToolCall, Truncated, Failed {}

record Answer(String text) implements LlmReply {}
record ToolCall(String tool, Map<String, String> arguments) implements LlmReply {}
record Truncated(String partialText) implements LlmReply {}
record Failed(int httpStatus, String error) implements LlmReply {}

Then pattern matching for switch handles each one, and pulls the fields out of the record in the same line:

static String handle(LlmReply reply) {
    return switch (reply) {
        case Answer(String text) -> "Show the user: " + text;
        case ToolCall(String tool, var args) -> "Run " + tool + " with " + args;
        case Truncated(String partial) -> "Ask for more tokens, got: " + partial;
        case Failed(int status, String error) when status == 429 -> "Slow down and retry: " + error;
        case Failed(int status, String error) -> "Give up, HTTP " + status + ": " + error;
    };
}

Output for one of each:

Show the user: Sorry about that! I've started your refund.
Run refundOrder with {orderId=1234}
Ask for more tokens, got: Sorry about that! I've st
Slow down and retry: Rate limit reached
Give up, HTTP 401: Invalid API key

Here is the part that matters. There is no default branch. Because the interface is sealed, the compiler knows every possible kind of reply. Next month, when you add a Refused reply for answers the model declines to give, every switch that doesn’t handle it stops compiling. The compiler shows you every place you need to update, before your users find the gap.

The when guard lets you treat a rate limit (429, worth retrying) differently from other failures, without a pile of if statements.

3. Text blocks: prompts you can read

A prompt is often several lines of instructions. Squeezing that into a normal string with \n and + makes it hard to read and easy to break. A text block keeps the prompt looking like the text the model will see:

String prompt = """
    Read the email below and return ONLY a JSON object with these fields:
    number (string), customer (string), total (number), items (array of strings).

    Email:
    <<<
    %s
    >>>
    """.formatted(emailText);

Two habits worth building:

  • Fill in values with formatted(), so the template stays in one piece and you can see where the data goes.
  • Fence off text that came from users or documents, here with <<< and >>>, and tell the model that’s the data. It makes it clearer to the model what is an instruction and what is content. This helps against prompt injection (text that tries to give the model new orders), but it doesn’t fully stop it. Never let the model’s answer trigger a risky action without your own checks.

When a prompt grows long, move it into a file under src/main/resources and load it at startup. Text blocks are perfect for short and medium prompts that live next to the code using them.

4. Virtual threads: many slow calls at once

An LLM call spends almost all its time waiting: for the network, and for the model to write. With classic platform threads, each waiting call holds an operating-system thread, and you can only have a few thousand of those. Virtual threads are cheap threads managed by the JVM. When one is waiting, it steps aside and lets others run, so you can have thousands of them.

The best part: you keep writing plain blocking code. HttpClient.send just works. No callbacks, no reactive chains.

Here we summarise 100 support tickets. Each LLM call is faked with a one-second sleep so you can run it without a model:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;

public class ParallelSummaries {

    // At most 10 calls to the LLM at the same time, so we stay under the provider's rate limit
    static final Semaphore LIMIT = new Semaphore(10);

    // Stand-in for a real LLM call (like LlmClient.chat). It just waits one second.
    static String summarise(String ticket) throws InterruptedException {
        Thread.sleep(1000);
        return "Summary of " + ticket;
    }

    static String summariseWithLimit(String ticket) throws InterruptedException {
        LIMIT.acquire();
        try {
            return summarise(ticket);
        } finally {
            LIMIT.release();
        }
    }

    public static void main(String[] args) throws Exception {
        List<String> tickets = new ArrayList<>();
        for (int i = 1; i <= 100; i++) tickets.add("ticket-" + i);

        long start = System.currentTimeMillis();

        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            List<Future<String>> futures = new ArrayList<>();
            for (String ticket : tickets) {
                futures.add(executor.submit(() -> summariseWithLimit(ticket)));
            }
            for (Future<String> f : futures) {
                f.get();   // waits for each summary
            }
        }

        long seconds = (System.currentTimeMillis() - start) / 1000;
        System.out.println(tickets.size() + " summaries in about " + seconds + " seconds");
    }
}
100 summaries in about 10 seconds

One by one, this would take about 100 seconds. With virtual threads and a limit of 10 at a time, it takes about 10.

Notice the Semaphore. Virtual threads make it easy to start 100 calls at once, but your LLM provider limits how many requests per minute you may send. Start them all and you get a wall of 429 errors. The semaphore is a simple gate: only 10 calls are in flight at any moment, and the rest wait their turn, which costs almost nothing on a virtual thread. Set the number to what your provider’s rate limit allows.

In a Spring Boot 3.2+ app, you can turn on virtual threads for request handling with one property, spring.threads.virtual.enabled=true. Then each web request that calls an LLM waits on a cheap virtual thread.

5. Small helpers worth knowing

  • var keeps long generic types short: var futures = new ArrayList<Future<String>>();. See Java var.
  • Sequenced collections: chat code often needs the latest message. Since Java 21, it’s just history.getLast(), instead of history.get(history.size() - 1). See sequenced collections.

Quick reference

AI problem Java feature Since
JSON requests and responses Records Java 16
Trusting the model’s JSON answer Records with a compact constructor Java 16
Many kinds of reply Sealed interfaces Java 17
Handling every reply safely Pattern matching for switch, record patterns Java 21
Long prompts in code Text blocks Java 15
Many slow calls at once Virtual threads Java 21
Getting the latest message Sequenced collections Java 21

If you are on Java 17, you have records, sealed types and text blocks already. Java 21 adds the pattern matching and virtual threads that tie it all together, which is a good reason to upgrade. Our Java 21 features guide covers the rest.

Key takeaways

  • Use records for every request, response and message. Add checks in the compact constructor.
  • For structured output, ask for JSON and read it into a record. The record decides what is acceptable, not the model.
  • Model every outcome of a call as a sealed interface, and handle it with a switch with no default. New cases then show up as compile errors.
  • Write prompts as text blocks with formatted(), and fence off user-supplied text.
  • Use virtual threads to run many LLM calls at once with simple blocking code, and a semaphore to stay under rate limits.

Frequently asked questions

Which Java version should I use for AI apps?

Java 21 or newer. It has every feature in this article. Java 25 is the newest long-term support release and also fixes virtual threads blocking inside synchronized code, so it is a great choice for a new project.

How do I get structured JSON output from an LLM in Java?

Ask the model to reply with JSON only, describe the fields in the prompt (or use the API’s JSON or schema option if it has one), then parse the reply with Jackson into a record. Put validation in the record’s compact constructor so bad answers are rejected.

Are virtual threads good for calling LLM APIs?

Yes. LLM calls spend most of their time waiting, which is exactly the job virtual threads are built for. Combine them with a limit, like a Semaphore, so you don’t exceed your provider’s rate limit.

Why use a sealed interface instead of an enum or a status string?

Each kind of reply carries different data: an answer has text, a tool call has a name and arguments, a failure has a status code. A sealed interface of records keeps that data typed, and the compiler checks that every kind is handled.

Do I need Java 21 to use records and text blocks?

No. Text blocks came in Java 15, records in Java 16 and sealed classes in Java 17. Pattern matching for switch, record patterns and virtual threads need Java 21.

What’s next

That completes the Foundations of Java for AI Engineers: why Java, how LLMs work, calling an LLM with plain Java, and the modern Java features that make the code clean. Next in the series, we move to the frameworks, starting with Spring AI’s ChatClient, and what it does on top of the HTTP call you now understand.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.