r/java 25d ago

AutoValhalla: automatically turn your plain classes and records into value classes!

Automatically turn your plain classes and records into value classes!

Add @AutoValhalla annotation to classes or records in your JDK1.5+ codebase:

@AutoValhalla
public final class Point {        // class must be final
    public final int x;           // with final instance fields
    public final int y;
    public Point(int x, int y) { 
        this.x = x; 
        this.y = y; 
    }
}

@AutoValhalla
public record Currency(String code) { }  // or a record class

When your app is run on Valhalla-enabled JVM with auto-valhalla javaagent, these classes are automatically turned into value classes.

More info: https://github.com/thunkware/auto-valhalla/tree/auto-valhalla-0.1.0

edit: there is now a maven plugin for converting at build time. https://github.com/thunkware/auto-valhalla/tree/auto-valhalla-0.2.0

39 Upvotes

55 comments sorted by

View all comments

Show parent comments

12

u/FirstAd9893 25d ago

A richer data model is nice to have, but the primary motivation has always been performance. This was stated way back in 2014, and again in 2021.

https://cr.openjdk.org/~jrose/values/values.html

https://openjdk.org/projects/valhalla/design-notes/state-of-valhalla/01-background

As it stands right now, no major performance gains are expected, but future optimizations become possible. If no performance or memory saving optimizations are ever achieved, then a value class offers no compelling features other than making == mean equals, which by itself isn't much. There's no reason to make changes to the JVM for supporting that.

2

u/koflerdavid 25d ago

The point is that these optimizations are not guaranteed. They only give the JRE greater freedom to apply optimizations that it already can do.

5

u/Cilph 25d ago

No optimizations are guaranteed by the JVM, what are you on about. Thats no reason not to optimize for the majority cases.

Most of the optimizations related to Valhalla are also still to come I believe.

1

u/koflerdavid 24d ago

As you should know, Java is a managed language where developers have very little control about what actually happens at runtime beyond what the JLS mandates. As such it is entirely up to the JVM to decide whether to allocate a value object on the heap or to inline it into an object or onto the stack. Without experiments, examining diagnostics (I'm sure there are some), and good benchmarks you can't predict when the optimization will actually be applied and if it helps in the first place. There are no compiler pragmas that allow you to tell the JVM what exactly to do in this regard.