What does the transient keyword do?
Quick Answer
transient marks a field to be excluded from the default serialization process — when an object is serialized, transient fields are simply skipped (written as their type's default value on deserialization) rather than included in the byte stream. It's used for fields that are either not meaningfully serializable (a Thread, a database connection) or that shouldn't be persisted (a cached/derived value, sensitive data like a plaintext password).
Detailed Answer
transient marks a field so the default Java serialization mechanism skips it — its value is simply not written to the serialized byte stream, and on deserialization it's restored to its type's default (null for objects, 0/false for primitives), regardless of what it held before serialization.
class Session implements Serializable {
String userId; // serialized normally
transient Connection dbConn; // skipped — Connection isn't serializable anyway
transient String cachedToken; // skipped — recomputed after deserialization, not persisted
}
Typical reasons to mark a field transient:
- The field's type isn't serializable and can't reasonably be made so (a
Thread, aSocket, a databaseConnection) — including it would throwNotSerializableExceptionat serialization time. - The value is derived/cacheable and cheaper to recompute than to persist and restore.
- The value is sensitive and shouldn't be persisted to disk or sent over the wire as part of the serialized form (e.g., a decrypted secret held only in memory).
If a class needs custom logic to restore a transient field's value after deserialization (rather than leaving it at its default), it can implement a private readObject(ObjectInputStream) method that calls defaultReadObject() for the normal fields and then manually recomputes/reinitializes the transient ones.