Versions Compared

Key

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

...

Code Block
bgColor#FFcccc

class SensorData implements Serializable {
  // 1MB of data per instance!
  ... 
  public static SensorData readSensorData() {...}
  public static boolean continueReading() {...}
}

class SerializeSensorData {
  public static void main(String[] args) throws IOException {
    ObjectOutputStream out = null;
    try {
      out = new ObjectOutputStream(
          new BufferedOutputStream(new FileOutputStream("ser.dat")));
      while (SensorData.continueReading()) {
        // note that each SensorData object is 1MB in size
        SensorData sd = SensorData.readSensorData();
        out.writeObject(sd);
      }
    } finally {
      out.close();
    }
  }
}

Compliant Solution

This compliant solution takes advantage of the known properties of the sensor data by resetting the output stream after each write. The reset clears the output stream's internal object cache; consequently, the cache no longer maintains references to previously-written SensorData objects. The garbage collector is able to collect SensorData instances that are no longer needed.

Code Block
bgColor#ccccff
class SerializeSensorData {
  public static void main(String[] args) throws IOException {
    ObjectOutputStream out = null;
    try {
      out = new ObjectOutputStream(
          new BufferedOutputStream(new FileOutputStream("ser.dat")));
      while (SensorData.continueReading()) {
        // note that each SensorData object is 1MB in size
        SensorData sd = SensorData.readSensorData();
        out.writeObject(sd);
        out.reset(); // reset the stream
      }
    } finally {
      out.close();
    }
  }
}

Risk Assessment

Memory and resource leaks during serialization can consume all available memory or crash the JVM.

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="a7c176addfc40721-0584148f-41364462-91fa9149-4a420f5c0e9fe1c677f2965c"><ac:plain-text-body><![CDATA[

[[API 2006

AA. Bibliography#API 06]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="0eba6c9dc5828fa4-53c6ccac-4a054a1a-a6b8ab00-d12177564427a6263ffb08d8"><ac:plain-text-body><![CDATA[

[[Harold 2006

AA. Bibliography#Harold 06]]

13.4. Performance

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="b3d8b8485ee1ee31-9c1ef245-4c324300-bfc48ae4-90c310aa559946438e8b61c4"><ac:plain-text-body><![CDATA[

[[Sun 2006

AA. Bibliography#Sun 06]]

"Serialization specification"

]]></ac:plain-text-body></ac:structured-macro>

...