Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding duplicate objects in Java deserialization

I have two lists (list1 and list2) containing references to some objects, where some of the list entries may point to the same object. Then, for various reasons, I am serializing these lists to two separate files. Finally, when I deserialize the lists, I would like to ensure that I am not re-creating more objects than needed. In other words, it should still be possible for some entry of List1 to point to the same object as some entry in List2.

MyObject obj = new MyObject();
List<MyObject> list1 = new ArrayList<MyObject>();
List<MyObject> list2 = new ArrayList<MyObject>();
list1.add(obj);
list2.add(obj);

// serialize to file1.ser
ObjectOutputStream oos = new ObjectOutputStream(...);
oos.writeObject(list1);
oos.close();

// serialize to file2.ser
oos = new ObjectOutputStream(...);
oos.writeObject(list2);
oos.close();

I think that sections 3.4 and A.2 of the spec say that deserialization strictly results in the creation of new objects, but I'm not sure. If so, some possible solutions might involve:

  1. Implementing equals() and hashCode() and checking references manually.
  2. Creating a "container class" to hold everything and then serializing the container class.

Is there an easy way to ensure that objects are not duplicated upon deserialization?

Thanks.

like image 940
YGL Avatar asked Apr 19 '10 06:04

YGL


1 Answers

After deserialization of the second list you could iterate over it's the elements and replace duplicates by a reference to the first list.

According to 3.7 The readResolve Method the readResolve() method is not invoked on the object until the object is fully constructed.

like image 177
stacker Avatar answered Oct 18 '22 04:10

stacker