Course contentsShow
← Java
Lesson 2145 of 2,87042. SerializationFree lesson

Maintaining Read/Write Symmetry

Ensure data written in writeObject is read in exactly the same order and types in readObject to prevent corruption.

Maintaining Read/Write Symmetry

You'll learn why matching the order and types between writeObject and readObject is critical to prevent data corruption.

When you customize serialization with writeObject and readObject, you're essentially creating a custom data format. Just like a conversation, what you say must match what the listener expects to hear—in the exact same order.

The Core Principle

Symmetry means exact correspondence. Every piece of data you write in writeObject must be read back in readObject in the same order and using the same data type. If you write an int followed by a String, you must read an int followed by a String—no exceptions.

Think of it like packing a suitcase and unpacking it. If you pack shoes, then shirts, then pants, you must unpack in that same order. Otherwise, you'll pull out a shoe when expecting a shirt, and everything becomes chaos.

The Danger of Asymmetry

If your read/write operations don't match:

  • You'll read the wrong bytes as the wrong type
  • Data will be corrupted or misinterpreted
  • You'll likely get StreamCorruptedException, EOFException, or mysterious wrong values
  • The object will be in an invalid state

Example Pattern

private void writeObject(ObjectOutputStream out) throws IOException {
    out.defaultWriteObject();
    out.writeInt(customValue);      // 1. Write int
    out.writeUTF(customString);     // 2. Write String
}

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    customValue = in.readInt();     // 1. Read int (SAME ORDER)
    customString = in.readUTF();    // 2. Read String (SAME ORDER)
}

Notice the perfect mirroring: writeInt/readInt, then writeUTF/readUTF, in identical sequence.

Key Takeaway: Always maintain perfect symmetry between writeObject and readObject—every write operation must have a matching read operation in the same order and with the same type to ensure correct deserialization.