I did a serialization test with Java. I found that Java serialization can handle circular references properly. But how does Java serialization solve circular reference problems?
The following code works correctly:
public class SerializableTest {
static class Employee implements Serializable{
private static final long serialVersionUID = 1L;
String name;
int age;
Employee leader;
public void say(){
System.out.println("my name is " + name + ". and I'm " + age + " years old.");
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectOutput objectOutput = new ObjectOutputStream(new FileOutputStream(new File("tempPath")));
Employee employee = new Employee();
employee.name = "Tom";
employee.age = 41;
employee.leader = employee;
employee.say();
objectOutput.writeObject(employee);
ObjectInput objectInput = new ObjectInputStream(new FileInputStream(new File("tempPath")));
Employee readEmployee = (Employee) objectInput.readObject();
readEmployee.say();
readEmployee.leader.say();
}
}
Java Serialization uses an IdentityHashMap
to map every reference it tries to serialize to an id. The first time it serializes an object it writes its contents and its id. After that, it writes just the id allowing circular references and one copy of an object no matter how many times it is referenced.
The downside is that if you keep the Object stream and don't call reset()
it will retain every object you have ever sent resulting in memory usage increasing. Also if you change an object and send it again, the changes won't be apparent as it only sends the reference to the object again.