MaintainJ Blog

May 10, 2012

The tricks of Java serialization

Filed under: Uncategorized — maintainj @ 4:59 pm

Whenever I start looking deeper into Java’s serialization mechanism, I seem to learn something new. Here is something I learned yesterday. Read the code snippet below and try to guess the output.


class DataHolder implements Serializable{
String data = "data";
public class SerializationTester {
static String serFile = "test.ser";
static void write() throws Exception{
//Create an object and write to ObjectOutputStream
DataHolder dh = new DataHolder();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFile));

//Change the state and write to the same stream again = "New data";
static void read() throws Exception{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(serFile));
DataHolder dh1 = (DataHolder)ois.readObject();
DataHolder dh2 = (DataHolder)ois.readObject();
System.out.println( + "--" +;
public static void main(String[] args) throws Exception{

What do you think will be the output? It’s ‘data–data’. The new value set to the field is not written to the stream. To make the Java serialization mechanism write the new value to the stream, we have to reset the stream by calling

Check this article on Serialization to understand what’s going on. The part that’s of interest to us is below:


… consider the situation in which an object is written to a stream and then written again later. By default, an ObjectOutputStream will maintain a reference to an object written to it. That means that if the state of the written object is written and then written again, the new state will not be saved! Here is a code snippet that shows that problem in action:

10 ObjectOutputStream out = new ObjectOutputStream(...);
20 MyObject obj = new MyObject(); // must be Serializable
30 obj.setState(100);
40 out.writeObject(obj); // saves object with state = 100
50 obj.setState(200);
60 out.writeObject(obj); // does not save new object state

There are two ways to control that situation. First, you could make sure to always close the stream after a write call, ensuring the new object is written out each time. Second, you could call the ObjectOutputStream.reset() method, which would tell the stream to release the cache of references it is holding so all new write calls will actually be written. Be careful, though — the reset flushes the entire object cache, so all objects that have been written could be rewritten(top casinos online).


–Choudary Kothapalli.

Powered by WordPress