V6076. Recurrent serialization will use cached object state from first serialization.

The analyzer has detected a situation where an object already written to the stream is getting modified and written again to the same stream. Because of the specifics of the 'java.io.ObjectOuputStream' class, the modified state of the object being serialized will be ignored in favor of the original state.

Objects are serialized by the 'java.io.ObjectOuputStream' class, which caches them when writing to the stream. It means that the same object will not be serialized twice: the class will serialize it the first time but only write a reference to the exact same original object to the stream the second time. This is what the problem is about. If we serialize an object, modify it, and then serialize it again, the 'java.io.ObjectOuputStream' class will not be aware of the changes made and treat the modified object as the same object that was serialized earlier.

This is demonstrated by the following contrived example, where an object is serialized after modification, with its modified state ignored:

ObjectOutputStream out = new ObjectOutputStream(....);
SerializedObject obj = new SerializedObject();
obj.state = 100;
out.writeObject(obj); // writing object with state = 100
obj.state = 200;
out.writeObject(obj); // writing object with state = 100 (vs expected 200)
out.close();

There are two ways to avoid this behavior.

The simplest and most reliable solution is to create a new instance of the object and assign it a new state. For example:

ObjectOutputStream out = new ObjectOutputStream(....);
SerializedObject obj = new SerializedObject();
obj.state = 100;
out.writeObject(obj);
obj = new SerializedObject();
obj.state = 200;
out.writeObject(obj);
out.close();

The second solution is less trivial. It is based on using the 'reset' method of the 'java.io.ObjectOuputStream' class. Use it only when you understand what exactly and why you are doing because the 'reset' method will reset the state of all the objects previously written to the stream. The following example demonstrates the use of this method:

ObjectOutputStream out = new ObjectOutputStream(....);
SerializedObject obj = new SerializedObject();
obj.state = 100;
out.writeObject(obj);
out.reset();
obj.state = 200;
out.writeObject(obj);
out.close();

Bugs Found

Checked Projects
381
Collected Errors
13 764