Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Professor Jane who has three tutees, Able, Baker, and Charlie, all of whom have Professor Jane as their tutor. Issues can arise if 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 example above 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.

Code Block
bgColor#FFcccc
String filename = "serial";

 try {
	// Serializing using writeUnshared
    ObjectOutputStream oos = new ObjectOutputStream
        (new FileOutputStream(filename));
            
    oos.writeUnshared(jane);
    oos.close();
            
    // Deserializing using readUnshared
    ObjectInputStream ois = new ObjectInputStream
        (new FileInputStream(filename));
            
    Professor jane2 = (Professor)ois.readUnshared();
    ois.close();
            
    System.out.println("checkTutees returns: " +
        jane3.checkTutees());
    // prints "checkTutees returns: false"
            
} catch(Exception e) {
    System.out.println("Exception during deserialization" + e);
}

Compliant Solution

This compliant solution overcomes the problem of the noncompliant code example by using writeObject() and readObject(), ensuring that the tutor object referred to by the three students has a one-to-one mapping with the original Professor object.

Code Block
bgColor#ccccff
String filename = "serial";

try {
    System.out.println("Serializing using writeObject");
    ObjectOutputStream oos = new ObjectOutputStream
        (new FileOutputStream(filename));
            
    oos.writeObject(jane);
    oos.close();
            
    System.out.println("Deserializing using readObject");
    ObjectInputStream ois = new ObjectInputStream
        (new FileInputStream(filename));
            
    Professor jane2 = (Professor)ois.readObject();
    ois.close();
            
    System.out.println("checkTutees returns: " +
        jane2.checkTutees());
    // prints "checkTutees returns: true"
            
} catch(Exception e) {
    System.out.println("Exception during deserialization" + e);
}

Applicability

Using the writeUnshared() and readUnshared() methods may produce unexpected results.

Automated detection is straightforward.

Bibliography

...