Versions Compared

Key

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

...

According to the Java API [API 20112013], the writeUnshared() method

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 readObject and readUnshared from returning additional references to the deserialized instance obtained via this call.

This means that Consequently, the writeUnshared() and readUnshared() methods should not be used are unsuitable for round-trip serialization of data structures that contain reference cycles. It is also important to note that calls to the writeUnshared() and readUnshared() methods prevent sharing only of the object being serialized. Sharing of objects reached from references in the unshared object remains unchanged

Consider the following code example:

...

Code Block
bgColor#FFcccc
String filename = "serial";
try(ObjectOutputStream oos = new ObjectOutputStream(new 
      FileOutputStream(filename))) {
  // Serializing using writeUnshared
  oos.writeUnshared(jane);
} catch (Throwable e) {
  // Handle error
}

// Deserializing using readUnshared
try(ObjectInputStream ois = new ObjectInputStream(new 
      FileInputStream(filename))){
  Professor jane2 = (Professor)ois.readUnshared();
  System.out.println("checkTutees returns: " +
							                     jane2.checkTutees());
} catch (Throwable e) {
  // Handle error
}

...

Compliant Solution

This compliant solution overcomes the problem of the noncompliant code example by using uses the writeObject() and readObject(), ensuring 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
bgColor#ccccff
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
} 

...

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

 

...