CodeGym /Courses /JAVA 25 SELF /Object identity in binary serialization

Object identity in binary serialization

JAVA 25 SELF
Level 44, Lesson 3
Available

1. Introduction

In Java (and in OOP in general) every object has an identity — it is not just the set of values of its fields, but “who it is” in memory. Two objects can be “equivalent” (for example, a.equals(b) returns true) yet differ in identity (a != b). Identity is when two variables point to the same object in memory (a == b).

Why does this matter for serialization?

When you serialize (persist) an object graph (for example, a tree, a list, or just two objects that refer to the same nested object), it is important to preserve not only the field values, but also the structure of references between objects.

If your graph contains repeated references (multiple objects refer to the same nested object) or even cyclic references (A → B → A), then after deserialization these links must remain the same.

Example: you have two objects A and B, both referring to the same object C. After serialization and deserialization it should hold that a.c == b.c (the same object in memory). If serialization simply “copies” objects, you would get two different C instances after restoration — which is a different graph.

2. How ObjectOutputStream solves identity

Java uses a pair of classes for binary serialization: ObjectOutputStream (for writing) and ObjectInputStream (for reading).

ObjectOutputStream is not just “write an object to a file.” It is smart:

  • It tracks all objects that have already been serialized within a single write stream (one session).
  • If it encounters a reference to an object that has already been serialized, it does not write it again; instead, it writes a special “back reference” (reference handle).
  • During deserialization, ObjectInputStream rebuilds the structure so that back references point to the same object in memory.

This even works for cyclic references! That is, if you have A → B → A, serialization and deserialization won’t loop or crash: the references will be restored correctly.

How is this implemented?

Internally, ObjectOutputStream uses a special table (an identity map) that stores the objects already serialized. When it encounters a new object, it adds it to the table and serializes it fully. When it encounters an object from the table, it writes only a “back reference” (handle) to the stream.

3. Demonstration by example

Example 1: Graph with cyclic references (A → B, B → A)

import java.io.*;

class Node implements Serializable {
    String name;
    Node next;

    Node(String name) {
        this.name = name;
    }
}

public class CyclicSerializationDemo {
    public static void main(String[] args) throws Exception {
        Node a = new Node("A");
        Node b = new Node("B");
        a.next = b;
        b.next = a; // Cycle!

        // Serialization
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("cyclic.dat"))) {
            out.writeObject(a);
        }

        // Deserialization
        Node a2;
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("cyclic.dat"))) {
            a2 = (Node) in.readObject();
        }

        System.out.println("a2.name = " + a2.name); // A
        System.out.println("a2.next.name = " + a2.next.name); // B
        System.out.println("a2.next.next == a2: " + (a2.next.next == a2)); // true!
    }
}

Output:

a2.name = A
a2.next.name = B
a2.next.next == a2: true

Comment:
The cycle is preserved! After deserialization, a2.next.next points back to a2 again.

Example 2: Shared references (A → C, B → C)

import java.io.*;

class Wrapper implements Serializable {
    String name;
    Object ref;

    Wrapper(String name) { this.name = name; }
}

public class SharedReferenceDemo {
    public static void main(String[] args) throws Exception {
        Wrapper a = new Wrapper("A");
        Wrapper b = new Wrapper("B");
        Wrapper c = new Wrapper("C");

        a.ref = c;
        b.ref = c;

        // Serialization
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("shared.dat"))) {
            out.writeObject(new Wrapper[] {a, b});
        }

        // Deserialization
        Wrapper[] arr;
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("shared.dat"))) {
            arr = (Wrapper[]) in.readObject();
        }

        Wrapper a2 = arr[0];
        Wrapper b2 = arr[1];

        System.out.println("a2.ref == b2.ref: " + (a2.ref == b2.ref)); // true!
        System.out.println("a2.ref.name = " + ((Wrapper)a2.ref).name); // C
    }
}

Output:

a2.ref == b2.ref: true
a2.ref.name = C

Comment:
After deserialization, both references again point to the same object.

4. Relation to writeReplace and readResolve

In Java you can “intervene” in the (de)serialization process using special methods:

writeReplace() — called before an object is serialized. You can return a different object that will be serialized instead of the original.
readResolve() — called after an object is deserialized. You can return a different object that will be used instead of the just-created one.

Impact on identity:

  • If writeReplace() or readResolve() is used, the object returned by these methods is what goes into the reference table.
  • This can change identity: if readResolve() returns a new/different object, repeated references may point to different instances.
  • Be careful: you can both “break” identity and intentionally enforce it (a classic example is a Singleton via readResolve(), where all references after deserialization point to the same singleton).

5. Practice: code showing identity preservation

import java.io.*;

class Shared implements Serializable {
    String value;
    Shared(String value) { this.value = value; }
}

class Holder implements Serializable {
    String name;
    Shared shared;
    Holder(String name, Shared shared) {
        this.name = name;
        this.shared = shared;
    }
}

public class IdentityDemo {
    public static void main(String[] args) throws Exception {
        Shared c = new Shared("C");
        Holder a = new Holder("A", c);
        Holder b = new Holder("B", c);

        // Serialization
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("identity.dat"))) {
            out.writeObject(new Holder[] {a, b});
        }

        // Deserialization
        Holder[] arr;
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("identity.dat"))) {
            arr = (Holder[]) in.readObject();
        }

        Holder a2 = arr[0];
        Holder b2 = arr[1];

        System.out.println("a2.shared == b2.shared: " + (a2.shared == b2.shared)); // true!
        System.out.println("a2.shared.value = " + a2.shared.value); // C
    }
}

Output:

a2.shared == b2.shared: true
a2.shared.value = C

Comment:
The identity of object c is preserved: after deserialization, both references point to the same instance.

6. Conclusions and common mistakes

Mistake #1: serializing objects with shared references separately. If you write each object with its own ObjectOutputStream instance, the references between them will not be preserved — the deserialized instances will be different, even if originally it was the same reference.

Mistake #2: incorrect use of writeReplace() and readResolve(). These methods can substitute the object during (de)serialization, which changes its identity. If you don’t understand the mechanics, you can get unexpected instances on output.

Mistake #3: unexpected effects of shared mutable references. If multiple objects refer to the same mutable nested object (for example, a list), after deserialization this will remain so. A change in one place will affect all others.

Mistake #4: expecting “new” objects after serialization. Serialization does not create a “fresh” structure — it restores the original references as in the source. This can be surprising when working with caches or template objects.

1
Task
JAVA 25 SELF, level 44, lesson 3
Locked
Collaborative work with a shared document: preserving shared objects 📝
Collaborative work with a shared document: preserving shared objects 📝
1
Task
JAVA 25 SELF, level 44, lesson 3
Locked
Inventory management: object identity with separate storage 📦
Inventory management: object identity with separate storage 📦
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION