...
According to the Java API [API 2013], the writeUnshared() method
...
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 writeUnshared() and 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 writeUnshared().
...
However, when the data is deserialized using readUnshared(), the checkTutees() method no longer returns true because the tutor objects of the three students are different from the original Professor object.
Compliant Solution
This compliant solution uses the writeObject() and 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 true.
| Code Block | ||
|---|---|---|
| ||
String filename = "serial";
try(ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(filename))) {
// Serializing using writeUnshared
oos.writeObject(jane);
} catch (Throwable e) {
// Handle error
}
// Deserializing using readUnshared
try(ObjectInputStream ois = new ObjectInputStream(new
FileInputStream(filename))) {
Professor jane2 = (Professor)ois.readObject();
System.out.println("checkTutees returns: " +
jane2.checkTutees());
} catch (Throwable e) {
// Handle error
} |
Applicability
Using the writeUnshared() and readUnshared() methods may produce unexpected results when used for the round-trip serialization of the data structures containing reference cycles.
Bibliography
[API 2013] | Class |
...