Java - ObjectOutputStream writeUnshared() method



Description

The Java ObjectOutputStream 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).Specifically −

  • An object written via writeUnshared is always serialized in the same manner as a newly appearing object (an object that has not been written to the stream yet), regardless of whether or not the object has been written previously.

  • If writeObject is used to write an object that has been previously written with writeUnshared, the previous writeUnshared operation is treated as if it were a write of a separate object. In other words, ObjectOutputStream will never generate back-references to object data written by calls to writeUnshared.

While writing an object via writeUnshared does not in itself guarantee a unique reference to the object when it is deserialized, it allows a single object to be defined multiple times in a stream, so that multiple calls to readUnshared by the receiver will not conflict. Note that the rules described above only apply to the base-level object written with writeUnshared, and not to any transitively referenced sub-objects in the object graph to be serialized.

ObjectOutputStream subclasses which override this method can only be constructed in security contexts possessing the "enableSubclassImplementation" SerializablePermission; any attempt to instantiate such a subclass without this permission will cause a SecurityException to be thrown.

  • writeUnshared(Object o) writes an object without keeping a reference to it in the serialization stream.

  • This means −

    • If the same object is written multiple times using writeUnshared(), it will be serialized as a new copy each time.

    • Java will not reuse references, unlike writeObject() which writes shared references.

  • Useful for −

    • Preventing unintended object sharing.

    • Forcing deep copies on deserialization.

Declaration

Following is the declaration for java.io.ObjectOutputStream.writeUnshared() method.

public void writeUnshared(Object obj)

Parameters

obj − object to write to stream.

Return Value

This method does not return a value.

Exception

  • NotSerializableException − If an object in the graph to be serialized does not implement the Serializable interface.

  • InvalidClassException − If a problem exists with the class of an object to be serialized.

  • IOException − If an I/O error occurs during serialization.

Example - Usage of ObjectOutputStream writeUnshared() method

The following example shows the usage of ObjectOutputStream writeUnshared() method.

ObjectOutputStreamDemo.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) {
      Object s = "Hello World!";
      Object i = 1974;
      
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         // write something in the file
         oout.writeUnshared(s);
         oout.writeUnshared(i);

         // close the stream
         oout.close();

         // create an ObjectInputStream for the file we created before
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));

         // read and print what we wrote before
         System.out.println("" + ois.readUnshared());
         System.out.println("" + ois.readUnshared());
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Hello World!
1974

Example - Write the same object twice - with and without writeUnshared()

The following example shows the usage of ObjectOutputStream writeUnshared() method.

ObjectOutputStreamDemo.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) throws IOException, ClassNotFoundException {
      String filename = "unshared1.ser";

      Person person = new Person("Alice");

      // Write the same object twice using writeUnshared
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
         oos.writeUnshared(person); // First write
         oos.writeUnshared(person); // Second write (independent copy)
      }

      // Read both objects back
      try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
         Person p1 = (Person) ois.readUnshared();
         Person p2 = (Person) ois.readUnshared();

         System.out.println("Are p1 and p2 the same instance? " + (p1 == p2)); // false
      }
   }

   static class Person implements Serializable {
      String name;
      Person(String name) {
         this.name = name;
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result−

Are p1 and p2 the same instance? false

Example - Compare writeObject() vs writeUnshared() behavior

The following example shows the usage of ObjectOutputStream writeUnshared() method.

ObjectOutputStreamDemo.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) throws IOException, ClassNotFoundException {
      String filename = "compare.ser";

      Person shared = new Person("Bob");

      // Write with writeObject and writeUnshared
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
         oos.writeObject(shared);       // shared reference
         oos.writeUnshared(shared);    // unshared (written again)
      }

      // Read both back
      try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
         Person obj1 = (Person) ois.readObject();     // shared reference
         Person obj2 = (Person) ois.readUnshared();   // new instance

         System.out.println("Same object? " + (obj1 == obj2)); // false
      }
   }

   static class Person implements Serializable {
      String name;
      Person(String name) {
         this.name = name;
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result−

Same object? false
java_io_objectoutputstream.htm
Advertisements