Saturday, August 6, 2011

Serialization in Java

It’s been a while since I wrote anything, but today I felt the need to do so,because of an interesting issue I faced.

I, as part of my routine adhoc coding, was serializing java objects over a regular network socket. Objects to be serialized were POJOS. I was using the same stream to write multiple objects, as well as same objects multiple times with different states as shown below:

outputStream.writeObject(obj);
outputStream.writeObject(obj1);
outputStream.writeObject(obj2);
obj.someSetters();
outputStream.writeObject(obj);

In doing the above I used to get 2 different exceptions which occurred inconsistently:

  1. OptionalDataException
  2. StreamCorruptedException

The above exceptions were not reproducible and occurred sporadically.

Another issue that I faced was with the state of the object. It appeared that once an object is written to the stream, and then you change the state of the object,and try to rewrite the same object, the older version is written, and the newer changes are not reflected.

All the above issues were resolved with a call to outputStream.reset()

This call has to be made, if you want the stream to forget that it ever wrote anything. In common scenarios, once a stream is opened, and an object is written to it, it is closed. But if you are planning to write multiple objects to the same stream sequentially, I suggest you pay heed to the above scenario.

Would love to discuss more on the issue.

No comments:

Post a Comment