76 comments

[ 2.2 ms ] story [ 73.9 ms ] thread
You could probably a whole tech thriller on the evolution on Value Types in Java.

I’ve been reading the mailing lists and watched all videos on the topic and it is truly inspiring how much they managed to consolidate the design to something that always looked like java.

But while also going far deeper in granularity and understanding what it even means to be a value type and what optimizations can be done where

I appreciate the hard work that went into the things that did make it into Valhalla eventually, but:

> The model was powerful, but also mentally heavy

No it isn't! it is this interpretation that kills off the null-safety debate entirely. Saying you have a variable that cannot be null is not a mentally taxing distinction, especially since everything is labelled thoroughly.

> The team, faithful to the lesson “simplify the model for the user, even at the cost of the performance ceiling,” ultimately dismantled this dualism.

but it would have simplified it for the user.

The whole attitude and process around this and the other topics gives me very little faith that Java can be steered in a sensible direction here. The type system of a programming language is supposed to give convenient guarantees to the developer on a CPU that can only do numbers. There is no reason to reduce the optional(!) safety guarantees you can offer with the excuse of "too mentally taxing".

Hell, they even get there half way by recognising:

> the language model and the JVM model don’t have to overlap one hundred percent

I mean, I appreciate the huge engineering and design challenges here, but C# had non-null value types in 2002. It had generic value types in 2005 and it gained not-null “types with identity” in 2019 and no-one has batted an eyelid. (Indeed the type system support for value types still includes stuff Java isn’t even considering yet.)

Saying the mental model is too hard is basically saying your userbase is stupid. This stuff is not tricky.

The non-nullability issue seems to be about performance, not cognitive load (search the article for "writes atomically"), though not articulated.
I know its a faux pas in the Java world to acknowledge the existence of .NET, but how does this differ from .NET structs?

Value types, generic specialization, boxing - a quick skim makes it looks like they picked the same choices.

I made a comment on my understanding of the difference in implementation here: https://news.ycombinator.com/item?id=48606173

The ramifications for backwards compatibility is that the JVM won't have CLR features such as stackalloc (allocation of blocks of memory on stack), ref parameters (pass-by-reference of stack allocated value types), and all the other low-level/high-performance programming features available in the CLR.

The C# equivalent to Java ‘value class’ would be a class with a struct encapsulated for data. The data is flattened and allocated on the heap like Java. Similarly, escape analysis could stack allocate the class at runtime, and they can be scalarized like C# structs.

Java ‘value class’ only flattens if the total size of the class data fits within an atomic read/write op. You can force it to flatten, but you may have tearing like C# struct.

Even closer would be a C# ‘readonly record struct’. Though, it would be allocated on the stack unless you box it.
a few questions for the pros

> "The defining trait: no identity"

I get that this makes objects behave like primitive types. Maybe thats reason enough. But is it necessary for the performance boost and de-fluffing the objects? Seems like an orthogonal objective

> There’s a catch worth knowing about here, though: flattened data has to be readable and writable atomically (otherwise it risks “tearing” under concurrent access).

Isn't this a race condition and "undefined bahvior"..? Having to limit yourself to atomic sizes seems like a huge limitation, to accomodate what is most likely buggy code. Is all the effort only gunna help lil toy ColorRGB examples?

> The points array is a million pointers. Each pointer leads to a separate Point object lying somewhere on the heap.

Does this happen in actuality? One would assume the allocator tries to put stuff sequentially on the heap? Its not a guarantee as with these Value Types, but I'd think you could get similar-ish perf with prefetching in cache. I dunno whats happening under the hood.. But when writing Clojure apps the JVM always reserves absurd amounts of heapspace on my machine (to my annoyance). Id assume it can find some place to do contiguous allocations..

Which i guess gets me to my last question... where are the benchmarks broski? It all sounds great, but does it actually yield the insane speedups promised?

Great article, well written. But a benchmark would have been a nice "punchline"

> But careful: == looks at internal state, which isn’t always what the object represents, so for “is this the same data” comparisons keep using equals.

So == for value classes will basically be like memcmp(). That is a bit unfortunate, as it breaks encapsulation, exposing implementation details. Client code can use this to do case distinctions based on how a given value is internally represented. In a way, it’s worse than identity comparison, because identity comparison at least doesn’t expose internal state.

> Will I get a fast, flat `ArrayList<Point>`? Not yet.

Sad. Hope they can do this by the next LTS JDK.

From the article:

> In 1995, a memory access cost roughly the same as a CPU operation

Uhm... no?!

Here's a CS paper from 1993(!) about prefetching from cache(!!) because the cache was slower than the ALU. https://www.eecs.umich.edu/techreports/cse/93/CSE-TR-152-93....

It would perhaps make Java look a little bad to say that, in 1995, the prevailing attitude in certain circles was "If it's too slow, just wait for faster hardware - Moore's Law forever baby!" (Of course, Sun was selling, at the time, relatively fast hardware - the slower the software, the faster the required hardware)

A lot of the comments on here are a bit unfair on what is great work being done and even more awesome work (JEPs) in the pipeline for the future.

If Java was a child, imagine it being brought up by loving parents for the first few years (Sun) then it was thrown in a garage with some other children and neglected by its evil guardian (Oracle)

Neglected and unloved till JDK 8, its basically been playing catch up.

So when people say "oh so its now got structs or value types of X", yes it has but that's because it has been stunted in its development due to big bureaucratic and hostile corporate processes, but its free now and is getting love through the OpenJDK family.

I will continue to enjoy writing once and deploying anywhere!

Yeah. I agree. As a C# fan I discovered one day the change process and release notes. Like C# it does still have strong momentum in the language design space. It was a joy observing the last 10 releases.
I think this is quite similar to julia's handling of a struct. An array of mutable structs is just an array of pointers, where every pointer directs to the underlying structure. However with an array of structs (immutable is the default), there is no such indirection. The value of all fields are stored as array element (unless you have an array of heterogeneous elements).

If you want to change an element of such an array you need to create a new immutable struct which in practice it is quite fast, but a bit verbose to write.

I think a lot of people will file this under Java got structs.

That seems off. They're still objects, the new thing is that they can give up identity.

> The difference in the code is exactly one word: value.

What is unclear to me is why the decision to use a Point instance as a value or as a reference is made in the class definition rather than by the caller.

> Point[] point = new Point[10];

For the same class, I might need an array of values in one place and an array of references elsewhere within the same codebase.

It would really break the GC or the type system if you did that. If you return a single point out of a 100k long array, it has to pin the array? How do you track the GC root? Struct array elements need back pointers?

Conversely, if it auto-copies now you have to contend with runtime state changing the pass semantics?

I'll be interested in seeing the fallout of the (unavoidable) compat issue:

If I have a function that has a value `x` that erases to `java.lang.Object` (e.g. a parametric function with no lower bound); then it used to be safe to check for nullity and then synchronize on the object.

This is no longer safe: This can now throw `IdentityException` into your face. (it was _never_ a good idea)

In other words, a lot of old code must be reviewed.

I suspect that `-XX:DiagnoseSyncOnValueBasedClasses=2` will need to stay (with the semantics: if user tries to synchronize on identity-less object, then log a JFR event and make it a NOP, don't throw an exception)!

The current JEP text is a little too ambiguous to figure out whether that is the plan, anyways.

Looking into the negative comments is quite amusing. Not only do most of them contain technical inaccuracies, but of course, they also need to mention how great .NET supposedly has been from the beginning and how Java supposedly copied everything.

Let's take a stroll down memory lane. First of all, .NET literally started as a Java copy. On top of it, a non-cross-platform one for almost two decades! After having shamed Linux for so long Microsoft finally started porting .NET to other platforms in a non-backward compatible way. A lot of .NET proponents will tell you porting from legacy .NET to .NET Core (which was renamed once again to .NET) would be a quick fix, but it isn't. For example, the shop I used to work in had some important cryptographic libraries which were very painful to port. And then, there's .NET's simplistic garbage collector, which can be quite annoying because it tries to be a one-fit-all solution that basically cannot be tweaked at all, often resulting in unresolvable latency problems. There’s a lot of other stuff, like its ghetto-like ecosystem and the insane fragmentation of GUI libraries.

I also don't get the C# praise. Over the years, it has become quite the bloated language. It feels like Microsoft tries to implement every feature possible without realizing that an enterprise language is supposed to be streamlined. Async/await? Very ugly, very annoying. Java has solved this a lot better with virtual threads and structured concurrency.

I could go on, but these "language wars" are silly and pointless. Both platforms have their pros and cons. Besides, I have a lot of bad things to say about the JVM as well, but it's nice to see Valhalla finally beocming reality. Too late for me personally though.

stopped reading when i saw the AI illustration. wholly unnecessary, and it feels insulting to be fed slop like this...

if you really want a fun drawing get a human artist to do it. it doesn't need to be complicated, for example https://www.code-cartoons.com/ is mostly just stick figures and does an excellent job

but you don't even need any of that, a mermaid diagram would have worked perfectly fine too. instead you chose to use a technology that is known to be harmful

I have such an urge to comment "lgtm" on the 197k line change PR
Anyone know why the article's 4th picture is about the Jobs obituary gaffe? (It's not just for me, right?)
> The pull request alone adds over 197 thousand lines of code across 1,816 files.

And that across 2819 commits.

Wow, that’s insane.

> [IMAGE: the same Point[] array in two variants: “before” (an array of arrows → scattered boxes with headers) and “after” (a uniform strip of number pairs)]

The `Point[]` in the image tag of your LLM output crashed your image generation post processing.

The article has a section about that. For me, a struct in C/C# can be modified and is passed by copy while a value class can not be modified and is passed by value.

I do not think you can do stack allocation in Java.

Yup. By design, value classes will use cpu registers as a 1st priority instead.
Java = Oracle = Ellisons way of doing business

Unless your company forces you to use Java for new projects, consider a change

(comment deleted)
I'm wondering what this means for Kotlin now