Common NotSerializableException Scenarios
You'll learn: How to identify and avoid runtime errors caused by non-serializable fields when attempting to serialize an object.
The Problem: Non-Serializable Fields Break Serialization
Even if your class implements Serializable, serialization will fail at runtime if any of its instance fields reference objects whose classes are not serializable. Java can't convert these fields to bytes, so it throws a NotSerializableException.
Think of it like packing a suitcase: if one item inside cannot be packed (say, a live goldfish), you can't close the suitcase successfully—even if everything else is packable.
Common Scenarios That Trigger the Exception
1. Non-Serializable Object Fields
Your class is serializable, but it contains a field of a type that doesn't implement Serializable:
class Report implements Serializable {
private String title; // OK: String is Serializable
private Thread workerThread; // Problem! Thread is NOT Serializable
}
Attempting to serialize a Report will throw NotSerializableException because Thread cannot be serialized.
2. Collections Holding Non-Serializable Objects
A List or Map field itself may be serializable, but if it contains non-serializable objects, serialization fails:
class Container implements Serializable {
private List<Thread> threads = new ArrayList<>(); // ArrayList is serializable,
// but Thread elements are NOT
}
3. Anonymous Inner Classes or Lambdas
These can implicitly capture non-serializable outer references, causing hidden failures.
Key Takeaway:
A serializable class must ensure all its instance fields—and all objects they reference—are also serializable, or explicitly mark problematic fields as transient to exclude them from serialization.