Estimate project
← All posts

JEP 502 - Stable Values: a New Java 25 Feature Explained

This article takes a look at JEP 502 - Stable Values, a new feature coming with Java 25, our next LTS, scheduled for release in September. It will arrive as a first preview feature, so anything about it may still change.

5 min read
Javauncoverjavajava 25JEP502

This article takes a look at JEP 502 - Stable Values, a new feature coming with Java 25, our next LTS, scheduled for release in September. It will arrive as a first preview feature, so anything about it may still change.

What is Stable Value?

A StableValue <T> is a container holding exactly one value of type T. After it has been assigned, the value can no longer change. Think of it as an eventually final value.

Keep in mind that it’s the reference to the object that becomes immutable. The underlying object itself can still be modified.

Before Stable Values

Prior to Java 25, the final keyword was the way to get immutable data.

class Controller {
 private final EmailSender sender = new EmailSender();
}

This approach came with a few problems.

Any final field in our code must be set eagerly – either initialized in a constructor or declared as a static field. As a result, application startup can get slower. After all, not every field is needed right away, is it?

So perhaps we could drop the final keyword and write something like this:

class PetClinicController {

 private EmailSender sender = null;

 EmailSender getSender() {
   if (sender == null) {
     sender = new EmailSender();
   }
   return sender;
 }

 void adoptPet(User user, Pet pet) {
   // some logic here
   getSender().sendEmailTo(user, "You are great person!");
 }
}

That will work, won’t it? Startup gets faster. And indeed, it’s one way of dealing with the problem before Java 25. Sadly, it comes at a price.

  • The sender remains mutable; a different value can be assigned to the variable. Preventing that would require external tools or very careful code reviews.
  • A null pointer exception may occur when the field is accessed in some way other than through the getter.
  • “getSender” should ideally be thread-safe.
  • Yet even if we make it so, we stop the JVM from optimizing access to this field – for instance, with constant-folding.

Let’s put Stable Values to use

Let’s move the earlier example over to the new Java.

class PetClinicController {

 private final StableValue<EmailSender> sender = StableValue.of();

 EmailSender getSender() {
   return sender.orElseSet(() -> new EmailSender());
 }

 void adoptPet(User user, Pet pet) {
   // some logic here
   getSender().sendEmailTo(user, "You are great person!");
 }
}

The code looks almost the same, but now StableValue takes care of EmailSender’s nullability. Because of this, EmailSender can’t be called without first calling a method that retrieves the value.

Setting the value inside a StableValue is guaranteed to be thread-safe.

Stable functions

Stable Values serve as the basis for higher-level functional abstractions. At the moment, there are three kinds of stable functions.

Supplier:

This is a function evaluated just once; its result is then stored and returned. We could use it in our Controller, for instance.

class PetClinicController {

 private Supplier<EmailSender> sender = StableValue.supplier(()-> new EmailSender());

 void adoptPet(User user, Pet pet) {
   // some logic here
   sender.get().sendEmailTo(user, "You are great person!");
 }
}

intFunction:

A function that accepts an int parameter and computes a result from it, which the backing stable value storage then caches for that parameter value. It can come in handy in mathematics.

For example:

private final int SIZE = 3;
private final IntFunction<Integer> INT_FUNCTION = v -> {
 // Simulate expensive computation
 log("Computing value for: " + v);
 return 42;
};

private void runIntFunction() {
 var integerIntFunction = StableValue.intFunction(SIZE, INT_FUNCTION);

 log(integerIntFunction.apply(1));
 log(integerIntFunction.apply(1));
 log(integerIntFunction.apply(1));

 log(integerIntFunction.apply(2));
}

Calling runIntFunction gives the following response:

Computing value for: 1
Value: 42
Value: 42
Value: 42
Computing value for: 2
Value: 42

The main drawback is the size parameter: you have to specify in advance the range of the input parameter.

Exceeding the function’s size (e.g., 3) results in a runtime exception “Input not allowed: 3”

Function:

This is a more general variant of intFunction that lets you call your function with any input you like.

Here’s an example:

private Set<Color> KEYS = Set.of(Color.GRAY, Color.GOLDEN);
private Function<Color, HowCute> CUTE_FUNCTION = color -> {
 System.out.println("Computing cuteness for: " + color);
 return switch (color) {
   case RED -> HowCute.CUTE;
   case GRAY -> HowCute.VERY_CUTE;
   case GOLDEN -> HowCute.SUPER_CUTE;
 };
};

private void runCuteFunction() {
 var cuteFunction = StableValue.function(KEYS, CUTE_FUNCTION);

 log(cuteFunction.apply(Color.GOLDEN));
 log(cuteFunction.apply(Color.GOLDEN));
 log(cuteFunction.apply(Color.GOLDEN));

 log(cuteFunction.apply(Color.GRAY));

 log(cuteFunction.apply(Color.RED));
}

Calling runCuteFunction gives the following response:

Computing cuteness for: GOLDEN
Value: SUPER_CUTE
Value: SUPER_CUTE
Value: SUPER_CUTE
Computing cuteness for: GRAY
Value: VERY_CUTE
Exception in thread "main" java.lang.IllegalArgumentException: Input not allowed: RED

As you may have spotted, even when your function could handle a given input, you’ll get an “Input not allowed” exception if that input isn’t listed in the inputs parameter.

Stable collections

Unmodifiable collections can also be combined with stable values. Currently, only List and Map are available.

List<Integer> list = StableValue.list(SIZE, INT_FUNCTION);
Map<Color, HowCute> map = StableValue.map(KEYS, CUTE_FUNCTION);

The type doesn’t reveal that StableFunctions are used underneath. This seems handy for complex computations. It is limited, though, since a list can only work with intFunction. Hopefully more will come in the future.

Potential issues

Stable Values are straightforward and practical constructs. Still, it’s good to know the possible pitfalls that come with them.

Serializable:

Note that Stable Values don’t support Serializable. The JEP doesn’t say so, but the StableValue API documentation does.

So if you rely on serializable and plan to swap every final for Stable Values, you might run into trouble here.

Not using final:

When using StableValue, we must keep in mind that a different value can still be assigned to the variable. Nothing stops us from writing something like this (apart from common sense, naturally):

private StableValue<EmailSender> sender = StableValue.of();
void adoptPet(User user, Pet pet) {
 sender = null;
    // some logic here
 sender.orElseSet(...) //Null pointer exception
}

Every StableValue of yours should be marked final, but nothing forces you to do it. It’s the Optional<> story all over again.

Why, then, wasn’t a new keyword added – something like the “Lazy” known from other languages? Let’s examine the reasoning behind it.

What does this JEP aim for?

This JEP tells us that the author aimed to speed up Java application startup by separating the creation of stable values from their initialization, while ensuring it works in a multi-threaded environment and allows JVM optimization such as constant-folding.

What they do not aim to do is:

  • extend the Java programming language with a way to declare stable values,
  • change the semantics of final fields.

So although I’d personally love to see “Lazy”, I’m happy they’ve added something that helps us optimize our code. I’m looking forward to the next updates.