When objects are serialized using the
writeObject() method, each object is written to the output stream only once. Invoking the
writeObject() method on the same object a second time places a back-reference to the previously serialized instance in the stream. Correspondingly, the
readObject() method produces at most one instance for each object present in the input stream that was previously written by
writes an "unshared" object to the
ObjectOutputStream. This method is identical to
writeObject, except that it always writes the given object as a new, unique object in the stream (as opposed to a back-reference pointing to a previously serialized instance).
reads an "unshared" object from the
ObjectInputStream. This method is identical to
readObject, except that it prevents subsequent calls to
readUnsharedfrom returning additional references to the deserialized instance obtained via this call.
readUnshared() methods are unsuitable for round-trip serialization of data structures that contain reference cycles.
Consider the following code example:
Students are types that extend the basic type
Person. A student (that is, an object of type
Student) has a tutor of type
Professor. A professor (that is, an object of type
Professor) has a list (actually, an
ArrayList) of tutees (of type
Student). The method
checkTutees() checks whether all of the tutees of this professor have this professor as their tutor, returning
true if that is the case and
Suppose that Professor Jane has three students, Able, Baker, and Charlie, all of whom have Professor Jane as their tutor. Issues can arise if the
readUnshared() methods are used with these classes, as demonstrated in the following noncompliant code example.
Noncompliant Code Example
This noncompliant code example attempts to serialize the data from the previous example using
However, when the data is deserialized using
checkTutees() method no longer returns
true because the tutor objects of the three students are different from the original
This compliant solution uses the
readObject() methods to ensure that the tutor object referred to by the three students has a one-to-one mapping with the original
Professor object. The
checkTutees() method correctly returns
readUnshared() methods may produce unexpected results when used for the round-trip serialization of the data structures containing reference cycles.