Video in progress
What is serialVersionUID, and what happens if you don't write it?
It is a version number for the class: during deserialization the JVM compares the UID in the bytes with the current class's, and throws InvalidClassException if they don't match. If you don't write it, the JVM computes it from the class structure, and even a small change to the class makes old data unreadable.
📖 Answer
The automatically computed UID depends on the fields, methods, interfaces, even compiler-generated synthetic members. You added one method and the UID is different. Built it with a different compiler, and the UID can differ.
The result: sessions written to disk or Redis yesterday can't be read after today's deploy.
class CartItem implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
String sku;
int qty;
}
If you set the UID yourself, compatible changes keep working: when you add a new field, old data gets its default value; a removed field is simply ignored.
When you should bump the UID: when a field's type changes or its meaning breaks, that is, when you deliberately want to reject old data.
@Serial (Java 14+) is not required, but the compiler checks that you didn't misspell the name.
Sign up to mark studied questions and save your progress.