Some classes are inherently not serializable, because they represent resources outside of the manage Java environment. For example a FileOutputStream
can't really be serialized, because it represents an open file handle. The same is true for a Socket
: you can't save and restore "open sockets".
If you want to serialize some object that has a field of that type, then you'll have to mark those fields as transient.
Another reason to use transient
is when your class does some kind of internal caching. If, for example, your class can do calculations and for performance reasons it caches the result of each calculation, then saving that cache might not be desirable (because recalculating it might be faster than restoring it, or because it's unlikely that old cached values are of any use). In this case you'd mark the caching fields as transient.