207 points · by mfiguiere · 1y ago · 141 comments
I think about this a lot. What they had built was probably actually the best distributed file system within Facebook. It was similarly structured to unraid, and had good availability, durability, and space saving properties, but the approach to engineering was just so wrong headed in my opinion that I couldn't stomach it. Talking about it with other Java programmers within facebook, nobody seemed to mind. Final was just a hint after all.
> Perl does not enforce private and public parts of its modules as you may have been used to in other languages like C++, Ada, or Modula-17. Perl doesn't have an infatuation with enforced privacy. It would prefer that you stayed out of its living room because you weren't invited, not because it has a shotgun.
It's not exactly the same situation, but the point is, at the end of the day, you need to be able to rely on the people involved being willing to act reasonable. If you can't, then you're going to have problems.
---
I think the one thing that'd be nice is if I could somehow tell the JVM from a class that this class is open for final mutation rather than needing special flags passed into the JVM or special manifests in the Jar. It's often pretty clear to me, as a dev, what I when I need something to have final mutation (generally only with serialization objects).
For example,
@FinalMutatableByReflection
class Foo {
final String bar;
}
That'd allow me to transition code by just adding an annotation where it needs to be while also getting the benefit that final is really final everywhere else in code that isn't working with serialization. The sun.reflect.ReflectionFactory class only supports deserialization of objects whose classes implement java.io.Serializable
That is, you'll still be able to mutate final fields using the ReflectionFactory class, as long as that class inherits from SerializableThe problem with these various "integrity by default" options is that, in most cases, granting access to one effectively grants access to all. For instance, JNI, agent libraries, and JPMS options can each be used to bypass restrictions, making the separation between them largely illusory. Integrity, as framed here, is ultimately binary.
The unfortunate reality of the "integrity by default" crusade is that applications relying on libraries and tools that modify internals will continue to do so. The JDK hasn’t filled any gaps—it has only made an already delicate situation worse.
I think Java's handling of this transition compares very favourably to how other languages have handled similar transitions from some old model to a new one (or evolution in general) in terms of balancing the needs of both old and new projects.
8->11 was really a pain in the neck. 11->17 had some pain, but mostly was nothing serious.
17->21 has been painless.
And I have some projects running on 24 already with no problems.
The feature delivery has been great and we are getting pretty close to not needing to do anything but update the jdk to move forward.
Now, if only I could get devs to stop using lombok....
Semantics. Nobody demanded anything, if we want to play word games.
The java philosophy of final, makes software less extensible. This is the point; to have less overriding. Regardless of what the voting body decides (the meaning of users being subtly repurposed), the feature is anti-developer-agency past the point of healthy balance. I dont understand the enthusiasm.
I think there's only one case where i ended up relaxing integrity, and i'm hoping that's temporary - it will take more time to fix than i was willing to spend.
Sounds like a good evolution to me.
/me raises hand
Maybe if you want to mutate a field, don't mark it `final`?
I know, I know, people like to pretend things are one way and then hand their objects over to some horrid framework that breaks all the rules, because apparently giant web of mutable spaghetti is just fine, not an anti-pattern at all if you let some third-party bull$#!7 ORM/dependency-injection-framework-for-people-who-don't-like-constructors do it.
I was trying to think of an edge case with JsonB or JAXB that would be affected by this... but generally those frameworks have told you for quite awhile not to do stupid stuff like:
``` @Getter public class HelloMessage { @JsonbProperty private final String helloMessage; } ```
I can't think of any frameworks offhand that do this.
So I think it's safe to say "what about serialization?" is always going to be asked.
https://www.youtube.com/watch?v=2y5Pv4yN0b0&t=930s
Link is to the start of a sequence of three slides, the third of which is the slide in question.
For a more recent update on serialization, watch this talk “Serialization: A New Hope”: https://www.youtube.com/watch?v=mIbA2ymCWDs
Not a Java dev, so I thought it might be related to classes marked final somehow. But this seems like a reasonable proposal, at least in spirit.
My bet is that this will be yet another "checked exception" or "module system", where many applications now need to add "--add-opens". If you'll use ANY of many of the more popular frameworks or libraries you'll end up giving this assurance away, which will make library developers not able to rely on it and we're back to square one.
BTW, this JEP does not apply to setAccessible generally, as that's been restricted since JDK 16, but only to the particular (and more rare) use of setAccessible to mutate instance final fields. As the JEP says, static final fields, records' internal instance fields, and final instance fields of hidden classes cannot be mutated with that approach currently, so it's never been something that's expected to work in all cases.
There are, however, better solutions than a global test-mode flag that, invariably, will be used by some in production out of laziness, leaving no auditable record of what integrity constraints need to be violated and why. When a new team lead is appointed some years later they will have a hard time trying to reduce the entropy.
The better solutions will arrive in due course, but until then, build tools can automatically add most of the necessary flags. They should be encouraged to do that.
The theory is, go through the constructor. However, some objects are designed to go through several steps before reaching the desired state.
If GSON must deserialize {…, state:”CONFIRMED”}, it needs to call new Transaction(account1, account2, amount), then .setState(STARTED) then .setState(PENDING) then .setState(PAID) then .setState(CONFIRMED) ? That’s the theory of the constructor and mutation methods guarding the state, so that it is physically impossible to reach a wrong state.
There is a convention that deserialization is an exception to this theory: It should be able to restore the object as-is, after for example a transfer over the wire. So it was conventionally enabled to set final variables of the object, but only at initialization and only for its own good. It was assumed that, even though GSON could reach a state that was unachievable through normal means, it was, after all, the role of the programmer to add the right annotations to avoid this.
So how do we do it now?
The JEP says:
> the developers of serialization libraries should serialize and deserialize objects using the sun.reflect.ReflectionFactory class, which is supported for this purpose. Its deserialization methods can mutate final fields even if called from code in modules that are not enabled for final field mutation.
I don't know enough about the details here to say if that's sufficient, but I imagine that it at least should be, or if it's not, it will be improved to the point where it can be.
Maybe I don't know of your use case, but GSON/Jackson/Json type classes are strictly data that should only represent the data coming over the wire. If you need to further manipulate that data it sounds like the classes have too much responsibility.
The moment you need to run some code from another language on your code to generate some other code or whatever, they break down, while Gradle can be used for pretty much anything.
In other words, cargo/go only solve the cache/parallelize/resolve task dependencies problem for "hard coded" special cases, the moment you strive away from that you are in a world of pain.
Jokes aside, I thought the ability to mutate final fields was already removed/restricted after Java 17 :/
[Speculative optimizations] may not suffice in this case as future planned optimizations may wish to rely not only on immutability within the lifetime of the process, but also on the immutability of fields from one run of the application to the next.
Can someone elaborate a little more on what this means? I'm very surprised to hear that this was considered a blocker important enough to add all of this complicated machinery (and breaking several deserialization libraries...), when I've never even heard of such an optimization and can't imagine what sort of form it would takeSurprise #2! A popular open-source framework writes to final fields after object construction via generated bytecodes!... This optimization of the final field is *the* main optimization performed on final fields.
[0] https://web.archive.org/web/20121016082428/http://www.azulsy...
In C, at least, you can usually distinguish a true pointer to immutable data by using `restrict`.
I found this sentence confusing. You mean that modifying a value that has been const_cast is undefined behaviour only if the original variable was const right? Or something else?
If I understand correctly, here's a C++ example that has undefined behavior:
int foo() {
const int x = 42;
int *p = (int *)&x;
*p += 1;
return x;
}
foo() is UB, because it modifies the const object x, using a pointer cast to "cast away const". (Unfortunately, UBSan doesn't catch this, and I'm not aware of any sanitizer that does.) It's tempting to say that the pointer cast is "at fault" for the UB, but consider this very similar example that's not UB: int bar() {
int x = 42;
const int *const_p = &x;
int *p = (int *)&const_p;
*p += 1;
return x;
}
bar() has exactly the same pointer cast as foo(), however in this case the original x object is not const. That makes "casting away const" legal in this case. So the problem we're left with, is that knowing all the types isn't enough for us to tell whether this cast is going to cause UB. We have to know where the pointer originally came from, which might be in another function or another file.Programmers from their own mistakes? That's fine, but this is about cases where they set the "I really mean it and this isn't a mistake" flag.
The JVM's optimized code from programmers? Plausible, but aren't there already many cases where things get deoptimized based on run-time state changes?
It feels like someone just said "final means final!" without really thinking about the purpose of a JVM. Will there be a proposal to enforce checked exceptions, too?
That security model was obsolete and didn't fulfill its original purpose anymore. Most applications have never enabled it.
> Programmers from their own mistakes? That's fine, but this is about cases where they set the "I really mean it and this isn't a mistake" flag.
Not at all, the vast majority of code using this feature is part of libraries. Application developers are often not aware that this even happens. Anyway, it will also in the future be possible for developers to shoot themselves in the foot with this feature if they really want. They just have to work a bit harder for it.
> The JVM's optimized code from programmers? Plausible, but aren't there already many cases where things get deoptimized based on run-time state changes?
This is not a good thing because interpreted mode is terribly slow. The JIT exists to make Java fast, and developers should not made this harder than necessary.
> It feels like someone just said "final means final!" without really thinking about the purpose of a JVM. Will there be a proposal to enforce checked exceptions, too?
Do people really write `final` and are OK being aware that the field's value could still change after all?
Checked exceptions are already enforced. If you mean changing all exceptions to be checked: no, that would be a catastrophic backwards compatibility break, with no good upside.
The converse: people really write `field.setAccessible(true)` and are OK being aware that they are breaking another programmer's assumptions. That's the point of `field.setAccessible(true)` existing at all. It's monkey-patching.
Otherwise you might as well just delete the method and throw a `NoSuchMethodError` when someone calls it - nobody is calling `setAccessible(false)`
I have some experience hacking on Java Minecraft. Minecraft's code is what it is - take it or leave it. The more stuff you can do without modifying that code, the simpler the overall system is. If you can set a field with reflection then you don't need to modify that class to make the field public or non-final. In other words, monkey-patching. (Newer frameworks support more modification to Minecraft's own code with less effort, though.)
> This is not a good thing because interpreted mode is terribly slow. The JIT exists to make Java fast, and developers should not made this harder than necessary.
And it does that by being smart. It makes assumptions, compiles code given those assumptions, and recompiles it if they actually do not hold. For example, I expect that a method with a List parameter is most likely only ever called with one implementation of List, and the JVM knows this and will compile the method as if the parameter is ArrayList, and will compile the method for the specific implementation it sees in the first few calls, with a bail-out check forcing the method to be recompiled if it's ever not that implementation.
And if the JVM never sees a subclass of a certain class, it can statically dispatch all calls to references of that type, as if the class were final, even if it isn't marked final.
And, likewise, if the JVM never sees a write instruction to a certain field, except once in the constructor, it should be able to treat it as if the field were final, and avoid reloading it after method calls. If it loads a class with an instruction that writes that field, it has to recompile all those methods.
None of this should be news to the JVM engineers.
> And, likewise, if the JVM never sees a write instruction to a certain field, except once in the constructor, it should be able to treat it as if the field were final, and avoid reloading it after method calls. If it loads a class with an instruction that writes that field, it has to recompile all those methods.
Right now, many opportunities for this optimization cannot be used because `final` for non-static fields cannot be relied upon. If such a field modification happens, then it's far more difficult to locate all the code that is the result of constant propagation from that field's original value. The impact of changes in the other scenarios is quite limited in comparison.
> None of this should be news to the JVM engineers.
I know how JIT compilers work, and the OpenJDK team knows as well of course. Which is exactly why they pursue this change. Deoptimizing and recompiling simply sucks for performance because this is time the application could spend on far better things.
The security model was deprected, just like .NET dropped CAS in .NET Core, because it wasn't sound, and without applets, the OS security model was the right way.
Regardless, to me this isn't about performance, this is about "integrity" (to use the same term as in the JEP): consumers of my library should not be mucking about in private implementation details, and then inevitably complaining about problems to me when something breaks. If you need a feature that I don't expose, ask for it (or better yet, submit a patch).
Sure, I've used reflection to modify library internals before, but I recognize that whenever I do that I'm inviting a maintenance headache into my world. But some people just think things should always work, even when they are breaking them.
Up till now I always assumed the compiler would figure out on its own which variables were final, and optimize as needed. But this JEP makes it seem like there are optimizations that only happen if you manually mark the variable.
missed opportunity to call it "final final"
Seems like this way?
(yes yes, I know, that would break syntax... but please come up with something to discourage mutability)
Yeah I know there's ways around it, but then the author known what they told the other party to expect.
Even the JS standard library struggles with this. You just have to remember that .sort() modifies the array in place (and returns it), but .slice() does a shallow clone of the array. (Not a deep clone - that would be different again!)
I don't think this represents struggling. There needs to be some way to sort in place. Sometimes you need to sort a big array and don't want to allocate.
And there should be some way to clone the array without mutating. That's slice. So you how do you sort a clone? .slice().sort()
I think by far the biggest problem with ES .sort() is that number arrays don't sort numerically by default.
ISTM that there are almost always some kinds of mutable data structures present in non-trivial programs. And outside of the program, you have databases to directories of files that get mutated by users or other parts of a program. I think this is just a fact of life.
While bad code can exist in any language, I get worried about too much const in code, because it means they failed at both 1) and 2) and instead there are usually seriously tricky protocols that must be observed to make the thing work. I often ran into code where people were sprinkling const all over the code to lock things down but they fundamentally did not understand the design and made it nearly impossible to evolve, unless you used casts to get rid of const, which defeats the whole purpose.
I'm not saying const doesn't have value, but it's weapon #3, not weapon #1.
That's like using a hammer on a screw, clearly not the right way.
Thankfully I've never worked on such codebases.
The real problem is that it's not defined what is an object, and where, in a web of memory-objects pointing to each other, a conceptual object begins and ends. It's arbitrary. Also, what is const from one standpoint is not const from another. It's fluid. Type systems generally don't play well with that. The weirdness of the original `strstr()` C API showcases that problem well.
The only thing that makes some sense here is to keep it simple -- any struct-like thing is an individual object. Embedded objects of course inherit const-ness, but pointed-to objects do not.
I think the C++ model is also somewhat right -- any class can define individually through which indirections const-ness follows through. But the C++ way causes lots and lots of boilerplate.
In any case, my solution is to use const very sparingly, it can hardly be gotten right in practice beyond basic use. Being more rigid of const may have prevents 2-3 bugs in my life, but cost sooo much more time and required many rewrites to make it fit somehow.
I use const mostly for
- static const data
- some string-slice datatypes (these are often initialized from static const data like string literals).
- read-only function parameters passed by reference (Foo const *thing).Records?
What man that sees the ever-whirling wheel
Of Change, the which all mortal things doth sway,
But that thereby doth find, and plainly feel,
How Mutability in them doth play
Her cruel sports to many men's decay?
(Edmund Spenser, 1596)