Welcome everyone to the Inside Java Newscast, where we cover recent developments in the OpenJDK community. I'm Nicolai Parlog, Java Developer Advocate at Oracle, and today we're going to go over all the big additions in JDK 28, which are kind of amazing, hence the video length. This is easily the coolest release since 21.
JDK 28 went into ramp-down phase 1 two days ago and so its feature set is now fixed, which makes this a great time to take a closer look. And since we already discussed most of these features on this channel I'll keep intros short to make time for some less frequently discussed aspects that I'm positive will be new to many of you, plus add links to deeper discussions and all the JEPs in the description. We'll start with the final features before coming to incubating and preview features. Ready? Then let's dive right in!
▚PEM Encodings of Cryptographic Objects
JEP 542 finalizes the PEM API after three rounds of preview.
So if you want to exchange keys, certificates, or certificate revocations between systems, particularly when a human is involved, it's now straightforward to do that.
Suitable cryptographic objects implement the new marker interface BinaryEncodable, which does not have any methods
The functionality is hidden in the two new classes PEMEncoder and PEMDecoder that let you go back and forth between such encodable instances and byte arrays or strings.
Here's an interesting wrinkle, though:
BinaryEncodable is sealed because merely adding implements BinaryEncodable to a random class would not allow it to participate in the encoding and decoding mechanisms, so that'd be pointless and confusing.
But because there's one internal implementation of BinaryEncodable that we cannot reference and thus cannot list when we switch over BinaryEncodable instances, we must always use a catch-all, like a default branch.
That is intentional as it allows the JDK to add more implementations in the future without causing compile errors in our code.
And that's fine, but from a data-oriented programming perspective, it's kinda sad.
After all, there you want clients to not compile when a new implementation gets added to a sealed interface!
But that only makes sense if you have control over clients or are ok with breaking them and since the JDK does neither, it took this approach.
A blueprint for all libraries and frameworks that find themselves in the same situation.
▚Structured Concurrency
During its five years of incubation and preview, we have talked a lot about structured concurrency on this channel, so I'm gonna spare you the motivational speech. But I do want to go over the shape of the API as it's now being finalized in JDK 28 by JEP 543 because it evolved a lot over that time persiod and even since JDK 25.
You start by calling StructuredTaskScope.open() in a try-with-resources statement.
That guarantees that by the time you leave that statement, every thread the scope started has terminated.
No stray threads changing a shared data structure or otherwise causing havoc - concurrency starts and ends here!
Once you've got your scope, you fork, fork, fork all your subtasks and each of them gets executed in a new virtual thread, which becomes the child of the current thread - a relationship that is visible in the thread dump and very helpful for debugging.
Only the current thread can fork tasks with this scope.
If your subtasks want to fork more subtasks, they have to create their own StructuredTaskScopes.
After all that forking, you'll naturally be a bit exhausted and so you call join and wait for the results to roll in.
On success, join returns.
Otherwise it throws an exception, so your error handling belongs in the catch block.
What behavior constitutes "success" and how results and errors are created depends on the Joiner - so called because it configures the behavior of join.
The default, picked when none is passed to open, requires every subtask to succeed, but you can pick or implement another joiner.
It can define success criteria and result creation however it wants and its behavior is reflected in the three type parameters that Joiner and StructuredTaskScope carry:
- the type each subtask produces
- the type of the result
joinreturns - the type of exception
joinuses to report failure
There's a lot more to say about joiners, scope configuration (for example with thread factories), cancellation, error handling, composition of scopes across a larger task hierarchy, etc. but we have to cut it short here.
▚Garbage Collection Improvements
ZGC sees two great improvements:
One that we've recently doscussed in detail is JEP 546: adaptive heap sizing. In a nutshell, this lets ZGC adjust its heap size based on the needs of the application and the rest of the system. If lots of memory is available, expanding the heap is a cheap way to save on CPU time for garbage collections. But if the system needs that memory, ZGC can free up at least some of it at the cost of working harder.
The other is JEP 545: faster ZGC startup and warmup by acquiring and preparing physical memory more swiftly and efficiently. This involves starting with a ridiculously small heap of just 2 MB, aggressive expansion, huge pages, and more mumbo jumbo.
a very interesting topic that I hope to get Billy to do a Stack Walker episode on
You cannot imagine how happy Billy was when he first heard this very public announcement. Then again, you probably can. And I think he needs some more convincing, so let him know in the comments if you want that video.
JEP 545 has a very clear recommendation about the combination of these two features: Choose ZGC without either min or max heap size, enable adaptive heap sizing, sit back, and relax.
In other GC news, Shenandoah is now making its generational mode the default. JEP 535 contains more details on that.
▚AOT Code Compilation
JDK 28 expands the ahead-of-time cache with machine code that the just-in-time compiler generates during the cache's assembly. This considerably reduces an app's warmup time, mainly by taking the first steps towards peak performance very quickly. This means that, yes, the application reaches that point sooner, but it's also snappier from the get-go. Startup time can drop by another 10% to 20% to maybe 20% to 30% of a launch without a cache and instead of 10% of peak performance your first work load may launch closer to about 50% of it. For this to materialize during production, there are additional requirements on the similarity of training and production systems - JEP 544 has the details for you.
▚Interlude 🔪
Two more final changes in JDK 28:
- JEP 541 deprecates the macOS/x64 port for removal
- no continued preview of primitive patterns - they are out!
Before we move from cutting edge to bleeding edge, a quick reminder for what lives in between: JavaOne, the conference to learn about Java's trajectory. We just published the first talks - link in the description. It takes place in California in late March and early-bird tickets are only available until January 5th, so don't wait any longer.
▚Value Classes
Valhalla - let's go! And this time, we will talk about performance, too, at least in the abstract.
JEP 401 introduces value classes in a first preview.
If you enable preview features, 30 JDK classes (most notably the primitive wrapper types) turn into value classes.
And we can create value classes and value records by simply slapping value in front of class or record.
In many ways value classes are normal classes:
They are reference types and variables can be null.
They inherit from Object, can implement interfaces, and they work with generics.
What's different is that value objects have no identity.
As a consequence, you cannot synchronize on one, == compares their fields, and their instance fields are final, which we will come back to in the next section.
As for performance, you might think that the VM can use value objects' lack of identity to deduplicate instances that represent the same value. And it could certainly do that, but the larger potential is on the other side of that coin: There's nothing attached to any one instance that has to stick with that instance at all times, like object monitor information, for example, and so the VM can choose to duplicate a value and represent it in different ways, depending on what works best locally.
One such change in representation is scalarization, where an object is not passed via reference to the heap but by tearing it open, discarding the hull, and passing the fields directly in registers or on the stack. This is already routinely done for identity objects if escape analysis can prove that the identity, the hull, is not needed. For value objects, it never is, so this optimization is much more frequently applicable. In 2024, Brian said this about scalarization of value objects:
We get a lot of benefit from that regardless of what's happening on the heap
The other big optimization that Java is applying is flattening of references. Here, a field does not contain a pointer to a heap location but the value object's fields directly. Similarly, an array of value objects can become an array of just fields.
Flattening is much more limited than scalarization, though. First of all, Java does not want values to tear under concurrent access, so for mutable fields it insists on atomic writes. On common hardware, these come with considerable tradeoffs beyond 64 bits, though, so that's the limit. Usually, for now - optimizations can be highly context-specific and in flux.
But here's the sad part:
Because Java must generally assume that a field or array entry can be null and the field it wants to flatten might need all its bit patterns, like a long does, it must reserve an extra bit to store nullity.
That leaves at most 63 bits for the fields, less if there’s padding.
And there goes the long.
And the double.
And the int or float pair.
You can check what's happening by activating the diagnostic VM options PrintFieldLayout and PrintFlatArrayLayout.
If you did everything right, you should see NULLABLE_ATOMIC_FLAT next to a flattened field.
And this can obviously be a measurable performance boost!
There are many more Valhalla topics to talk about, but the rest is very much looking into the future and I reserve that for the video about Java's Plans for 2027, scheduled for mid-January. If you made it this far into this video, you're clearly the target audience, so make sure you're subscribed to this channel. And if you already are and feel awkward that subscription is idempotent, the thumbs up is right there.
▚Strict Field Initialization
So how final are those value class fields, really? An ordinary constructor can pass the instance under construction to other code before it's finished and then that other code can see the instance change from its uninitialized state to an initialized state, even if all fields are final. That's not how an immutable class is supposed to function and so we cannot have that for value classes.
So for those, the compiler enforces that all instance fields are assigned during early construction - a phase that is basically a static context where the only thing you can do with the instance under construction is read and write its fields. But this is about runtime integrity, too, and so the VM is involved as well. Thanks to JEP 539 and starting as a preview in JDK 28, javac can mark a field as strict, which lets the VM enforce the same behavior.
And, as you will have guessed, the Java compiler marks all instance fields of value classes and value records as strict. But, maybe a bit surprisingly, also of identity records, meaing all the records that we already wrote. The TL;DR behind that decision is that records are immutable, too, so they, too, should have this protection. It's a backwards incompatible change, though, but very little code out there actually does something it shouldn't be doing in a record constructor and the fix is pretty easy. That said, you may get compile errors about this if you enable preview features on JDK 28.
And, yes, technically the field in an immutable value class or record still changes (once, during construction), but nobody can see that happening, so it doesn't count. Immutability upheld!
▚Lazy Constants
The lazy constants API offers lazy, at-most-once initialization that, at the same time, enables aggressive just-in-time performance optimizations. This comes from close cooperation with the runtime where the reference to the lazily computed instance, once it gets created, is truly final and can't even be changed through reflection. It's basically a "delayed super-final" field, something the JDK calls a "stable field".
JEP 547 gives lazy constants their fourth preview and the API has gotten very simple during that time:
It has a static factory method of that takes a Supplier that produces the instance when it is first requested and it has an instance method get that returns said instance.
The supplier is executed at most once, even under concurrent access.
If it fails, every get throws - no retries.
Beyond that, List, Map, and Set each got a static factory method ofLazy:
List's takes the list's length and a function that computes each itemMap's takes a key set and a function that computes each valueSet's is a bit odd - it gets the "potential" set and a predicate that determines membership in the actual set
Of course in each of these cases the function or predicate is executed at most once per index, key, or candidate, respectively.
And that's the whole API. Not exactly rocket science, but the true value comes from the stable field that the VM can more aggressively optimize.
▚Simple JSON API
With JEP 540, JDK 28 incubates for the first time a simple JSON parsing and printing API.
Simple is important here - the goal is not to replace established JSON libraries.
I personally like to call this a "JSON starter set".
Because this is an incubating API, you need to compile and run with --add-modules jdk.incubator.json if you want to try it out.
Let's have a look at the API:
Parsing a document with Json.parse gives you an instance of the interface JsonValue.
There are two main ways to extract data from it:
- if you know the document's structure, you're likely to use
JsonValue's methodsasMap(),asList(),asString(),asDouble(), etc. that return the represented value in that form if it's of the right type or otherwise throw an exception - if you do not know the structure, you can instead pattern-match a
JsonValueand switch over its six specialized interfaces for JSON objects, arrays, strings, numbers, booleans, and null
And that's, like, 70% of the API. It's clearly focused on the essentials without bells and whistles. No data binding, no streaming, no parsing configurations, and also no syntax extensions, so no comments or trailing commas - this is pure RFC 8259. It even rejects duplicate keys instead of quietly picking a winner. As I said: simple.
▚Vector API
The vector API... JEP 548 is currently the youngest JEP and was also the last to be targeted to JDK 28. It gives the vector API its thirteenth incubation. Now, sorry, I read that wrong - I should've said ITS THIRTEENTH INCUBATION?!
For the first time in a long time it comes with a notable change though:
It now supports Vector<Float16>, a vector whose lanes hold 16-bit floating-point numbers in the IEEE 754 binary16 format.
The API was waiting for Valhalla's value objects, but that excu... explanation has run its course. My understanding is that once values have settled in and there's enough capacity, the vector API will adopt them and switch from incubation to preview. I hope to be able to tell you more about that in the next episode.
Until then, have a nice winter solstice and a happy new Gregorian year and I'll see you again in January 2027. Don't forget to like and subscribe and hug your loved ones. So long ...
