Video in progress
What values do `transient` fields have after deserialization, and how do you restore them?
They get default values: null, 0, false. Neither the constructor nor the field initializer is called. To restore them, you recompute the value in readObject after defaultReadObject().
📖 Answer
Many people get this wrong:
class PriceList implements Serializable {
private Map<String, Long> prices;
private transient Map<String, Long> index = new HashMap<>(); // null after deserialization!
}
Deserialization does not call the constructor of a Serializable class. The JVM calls the no-argument constructor of the first non-Serializable superclass (often Object) and fills the remaining fields from the stream. Initializers are part of the constructor, so index stays null and the first access gives an NPE.
The fix:
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject(); // reads the ordinary fields
index = buildIndex(prices); // we rebuild the transient one
}
readObject is also the right place for invariant checks: if prices == null, you throw InvalidObjectException. The stream can come from outside, so it can't be trusted.
When to use transient: caches, computed indexes, a Logger, a Thread, a socket, a DB connection: things that can't be serialized or make no sense to serialize. It is also put on secrets like passwords, but that is not protection, just a guarantee that they don't land in the stream.
Sign up to mark studied questions and save your progress.