Video in progress

What does the transient keyword do?

A field marked transient is not written during Java serialization. When the object is deserialized it gets the default value: null for objects, 0 for numbers, false for boolean.

📖 Answer

class Session implements Serializable {
    String userId;
    transient String password;     // must not land on disk
    transient Connection db;       // can't be serialized anyway
}

When it is used:

  • so secret data (a password, a token) doesn't end up in the bytes;
  • for things that can't be serialized: a thread, a socket, a DB connection;
  • for a cache that can be recomputed from other fields.

The trap: after deserialization the db field is null, and the first call throws an NPE. If needed, you have to restore it inside readObject or lazily.

One more thing: transient only affects Java's own serialization. Jackson does not take it into account by default (there is a MapperFeature.PROPAGATE_TRANSIENT_MARKER setting); to hide a field from JSON, use @JsonIgnore.